// ==PREPROCESSOR==
// @name "Biography, Covers, Albums, Title, Similar artist, Lyrics info.www.last.fm."
// @version "03032021"
// @author "kgena_ua"
// @feature "v1.4"
// @feature "watch-metadb"f
// ==/PREPROCESSOR==

// compatible with WSH panel mod and jscript panel

function RGB(r,g,b){
    return (0xff000000|(r<<16)|(g<<8)|(b));
}

function RGBA(r,g,b,a){
    return ((a << 24) | (r << 16) | (g << 8) | (b)); 
}

function getRed(color){
    return ((color >> 16) & 0xff);
}

function getGreen(color){
    return ((color >> 8) & 0xff);
}

function getBlue(color){
    return (color & 0xff);
}

function combineColors(c1, c2, k){ 
    var c1 = toRGB(c1);
    var c2 = toRGB(c2);
    k = k < 0 || k > 1 ? 0.5 : k;
    
    var r = Math.round(c1[0] * (1 - k) + c2[0] * k);
    var g = Math.round(c1[1] * (1 - k) + c2[1] * k);
    var b = Math.round(c1[2] * (1 - k) + c2[2] * k);
    
    return (0xff000000 | (r << 16) | (g << 8) | (b));
}

function toRGB(d){
    var d = d-0xff000000;
    var r = d >> 16;
    var g = d >> 8 & 0xFF;
    var b = d & 0xFF;

    return [r,g,b];
}

DT_LEFT = 0x00000000;
DT_RIGHT = 0x00000002;
DT_CENTER = 0x00000001;
DT_VCENTER = 0x00000004;
DT_SINGLELINE = 0x00000020;
DT_WORD_ELLIPSIS = 0x00040000;
DT_NOPREFIX = 0x00000800;
DT_BOTTOM = 0x00000008;

MF_ENABLED = 0x00000000;   
MF_GRAYED = 0x00000001;
MF_SEPARATOR = 0x00000800;

IDC_HAND = 32649;
IDC_ARROW = 32512;

ENTER = 13;
BACKSPACE = 8;
ESC = 27;
CTRLV = 22;

VK_SHIFT = 0x10;
VK_CONTROL = 0x11;
VK_PAGE_UP = 0x21;
VK_PAGE_DOWN = 0x22;
VK_END = 0x23;
VK_HOME = 0x24;
VK_LEFT = 0x25;
VK_UP = 0x26;
VK_RIGHT = 0x27;
VK_DOWN = 0x28;	
VK_DELETE = 0x2E;
VK_INSERT = 0x2D;

var ShiftDown = false;
var ControltDown = false;
		
var ww = 800, wh = 800;		
		
String.prototype.repeat = function(n){		
    return new Array(n + 1).join(this);		
}		
		
window.SetProperty(" - user", "");		
if (window.GetProperty(" - user") != "" ) window.SetProperty(" - user", "");
window.SetProperty("- user", "");		
if (window.GetProperty("- user") != "" ) window.SetProperty("- user", "");		
window.SetProperty("_".repeat(50), "");		
if (window.GetProperty("_".repeat(50)) != "" ) window.SetProperty("_".repeat(50), "");	

var text_alignment = [		
    ["Left", DT_SINGLELINE | DT_LEFT | DT_NOPREFIX, DT_BOTTOM | DT_SINGLELINE | DT_LEFT | DT_NOPREFIX],
    ["Center", DT_SINGLELINE | DT_CENTER | DT_NOPREFIX, DT_BOTTOM | DT_SINGLELINE | DT_CENTER | DT_NOPREFIX],
    ["Right" , DT_SINGLELINE | DT_RIGHT | DT_NOPREFIX, DT_BOTTOM | DT_SINGLELINE | DT_RIGHT | DT_NOPREFIX]	
];

var font_style = [		
    ["Normal", 0],
    ["Bold", 1],
    ["Italic" , 2],
    ["Bold italic" , 3]	
];

var text_alignment_h0 = window.GetProperty(" text Lock alignment : header 0 (0, 1, 2)", 0);
var text_alignment_h1 = window.GetProperty("text alignment : header 1", 2);
var text_alignment_h2 = window.GetProperty("text alignment : header 2", 2);
var text_alignment_t = window.GetProperty("text alignment : text", 0);
var text_alignment_ci = window.GetProperty("text alignment : text ci", 0);

var font_name_h0 = window.GetProperty(" text Lock font name: header 0", "Arial");
var font_name_h1 = window.GetProperty(" text: font name: header 1", "Arial");
var font_name_h2 = window.GetProperty(" text: font name: header 2", "Arial");
var font_name_t = window.GetProperty(" text: font name: text", "Arial");
var font_name_ci = window.GetProperty(" text: font name: text ci", "Arial");

var font_size_h0 = window.GetProperty("text: font size: header 0", 11);
var font_size_h1 = window.GetProperty("text: font size: header 1", 12);
var font_size_h2 = window.GetProperty("text: font size: header 2", 12);
var font_size_t = window.GetProperty("text: font size: text", 12);
var font_size_ci = window.GetProperty("text: font size: text ci", font_size_t - 1);

var font_style_h0 = window.GetProperty(" text Lock font style: header 0", 0);
var font_style_h1 = window.GetProperty("text: font style: header 1", 1);
var font_style_h2 = window.GetProperty("text: font style: header 2", 1);
var font_style_t = window.GetProperty("text: font style: text", 0);
var font_style_ci = window.GetProperty("text: font style: text ci", 0);

var font_size_min = window.GetProperty(" text: font size: min", 11);
var font_size_max = window.GetProperty(" text: font size: max", 16);

var text_shadow = window.GetProperty("text: shadow", false);
							
var h0_font, h1_font, h2_font, t_font, t2_font, tt_font;							
get_font();		
							
function get_font(){
    h0_font = gdi.Font(font_name_h0, font_size_h0, font_style_h0);	
    h1_font = gdi.Font(font_name_h1, font_size_h1, font_style_h1);							
    h2_font = gdi.Font(font_name_h2, font_size_h2, font_style_h2);
    t_font =  gdi.Font(font_name_t, font_size_t, font_style_t);
    ci_font =  gdi.Font(font_name_ci, font_size_t - 1, font_style_ci);
    t2_font = gdi.Font(font_name_t, font_size_t - 1, font_style_t);
    tt_font = gdi.Font(font_name_t, 12, 1);		
}   							
							
ColorTypeCUI = {							
    text: 0,        //					
    selection_text: 1,							
    inactive_selection_text: 2,     //						
    background: 3,      //						
    selection_background: 4,							
    inactive_selection_background: 5,							
    active_item_frame: 6							
};							
							
ColorTypeDUI = {							
	text: 0,						
	background: 1,						
	highlight: 2,						
	selection: 3						
};							

function get_color(){ 
    try { 	
        if (window.InstanceType == 0){							
            bg_color = window.GetColorCUI(ColorTypeCUI.background);							
            h1_color = window.GetColorCUI(ColorTypeCUI.text);
            h2_color = window.GetColorCUI(ColorTypeCUI.inactive_selection_text);		
            t_color = window.GetColorCUI(ColorTypeCUI.inactive_selection_text);		
        } else if (window.InstanceType == 1){ 							
            bg_color = window.GetColorDUI(ColorTypeDUI.background);							
            h1_color = window.GetColorDUI(ColorTypeDUI.text);
            h2_color = window.GetColorDUI(ColorTypeDUI.highlight);	
            t_color = window.GetColorDUI(ColorTypeDUI.highlight);							
        }	
    } catch(e){};
    try { 	
        if (window.InstanceType == 0){							
            bg_color = window.GetColourCUI(ColorTypeCUI.background);							
            h1_color = window.GetColourCUI(ColorTypeCUI.text);
            h2_color = window.GetColourCUI(ColorTypeCUI.inactive_selection_text);		
            t_color = window.GetColourCUI(ColorTypeCUI.inactive_selection_text);		
        } else if (window.InstanceType == 1){ 							
            bg_color = window.GetColourDUI(ColorTypeDUI.background);							
            h1_color = window.GetColourDUI(ColorTypeDUI.text);
            h2_color = window.GetColourDUI(ColorTypeDUI.highlight);	
            t_color = window.GetColourDUI(ColorTypeDUI.highlight);							
        }	
    } catch(e){};
    color_error = RGB(255, 125, 0);
    color_true = RGB(128, 255, 128);
    window.Repaint();	
}
					
var custom_colors = window.GetProperty(" colors: custom", false); 							
							
var c_bg_color = customColor(window.GetProperty(" color: background", "0-0-0"));							
var c_h1_color = customColor(window.GetProperty(" color: header 1", "255-255-220"));
var c_h2_color = customColor(window.GetProperty(" color: header 2", "180-180-180"));		 
var c_t_color = customColor(window.GetProperty(" color: text", "180-180-180"));							
							
get_color();							
ini_color();							
							
function on_colors_changed(){							
    get_color();							
    ini_color();							
}							
							
function ini_color(){							
    bg_color = custom_colors ? c_bg_color : bg_color;							
    h1_color = custom_colors ? c_h1_color : h1_color;
    h2_color = custom_colors ? c_h2_color : h2_color;
    t_color = custom_colors ? c_t_color : t_color;
}
							
function customColor(colour){							
   tmp = colour.split("-");							
   return (0xff000000 | (tmp[0]<<16) | (tmp[1]<<8) | (tmp[2]));							
}							
							
var colors_swap = window.GetProperty(" colors: swap", false);							
var tmp_h1_color = h1_color;
var tmp_h2_color = h2_color;	
var tmp_t_color = t_color;	

h1_color = !colors_swap ? tmp_h1_color : tmp_t_color;
h2_color = !colors_swap ? tmp_h2_color : tmp_h1_color;	
t_color = !colors_swap ? tmp_t_color : tmp_h1_color;
var color_selected_item = combineColors(bg_color, t_color , 0.6);

var rc_arr = [".",  "/",  ":",  "*",  "?",  '"',  "<",  ">",  "|"];

window.GetProperty(".reserved characters: " + rc_arr[0] + "  replace by", "no char");   // "."
window.GetProperty(".reserved characters: " + rc_arr[1] + "  replace by", "-");         // "/"
window.GetProperty(".reserved characters: " + rc_arr[2] + "  replace by", "no char");   // ":"
window.GetProperty(".reserved characters: " + rc_arr[3] + "  replace by", "x");         // "*"
window.GetProperty(".reserved characters: " + rc_arr[4] + "  replace by", "no char");   // "?"
window.GetProperty(".reserved characters: " + rc_arr[5] + "  replace by", "''");        // '"'
window.GetProperty(".reserved characters: " + rc_arr[6] + "  replace by", "_");         // "<"
window.GetProperty(".reserved characters: " + rc_arr[7] + "  replace by", "_");         // ">"
window.GetProperty(".reserved characters: " + rc_arr[8] + "  replace by", "no char");   // "\"
//window.GetProperty(".reserved characters:  " + rc_arr[9] + "  replace by", "no char");

check_char_enter();

function check_char_enter() {
    for (var i = 0; i < rc_arr.length; i++) {
        tmp = window.GetProperty(".reserved characters: " + rc_arr[i] + "  replace by");
        tmp = tmp.length > 1 && tmp != "no char" && tmp != "space" ? tmp[0] : tmp;
        window.SetProperty(".reserved characters: " + rc_arr[i] + "  replace by", tmp);
        if (/[\.\/\:\*\?\"\<\>\|\\]/g.test(tmp) || tmp == ""){
            window.SetProperty(".reserved characters: " + rc_arr[i] + "  replace by", "no char");
        }
        if (tmp == " ") window.SetProperty(".reserved characters: " + rc_arr[i] + "  replace by", "space");
    }
}

function symb(i){
    var tmp = window.GetProperty(".reserved characters: " + rc_arr[i] + "  replace by");
    tmp = tmp == "no char" ? "" : tmp;
    tmp = tmp == "space" ? " " : tmp;
    return tmp;
}

function clean(str) { 
    if (!str) return;
    var tmp = str.replace(/\./g, symb(0)).replace(/\//g, symb(1)).replace(/\:/g, symb(2)).replace(/\*/g, symb(3)).replace(/\?/g, symb(4)).replace(/\"/g, symb(5)).replace(/\</g, symb(6)).replace(/\>/g, symb(7)).replace(/\|/g, symb(8)).replace(/\\/g, "");
    return tmp.replace(/^\s+|\s+$/g,"").substr(0, 150);
}

function clean_ini(str){
    if (!str) return;
    return str.replace(/[\[\]']/g, "");
}

function trim(str){
    if (!str) return;
    return str.replace(/^\s+|\s+$/g, "").replace(/\s{1,}/g," ");
}

function title_case(str){
    if (!str) return "";
    var arr = str.toLowerCase().split(" ");
    for (i = 0; i < arr.length; i++){
        arr[i] = arr[i].charAt(0).toUpperCase() + (arr[i].substr(1));
    }
    return trim(arr.join(" "));
}

var fso = new ActiveXObject("Scripting.FileSystemObject");
var objShellApp = new ActiveXObject("Shell.Application");
var vbe = new ActiveXObject('ScriptControl');
vbe.Language = 'VBScript';
var htmlfile = new ActiveXObject('htmlfile');
var clipboardData = "";

var work_dir = window.GetProperty(" work directory", "tmp_Biography");	
work_dir = clean(work_dir);
window.SetProperty(" work directory", work_dir);
if (!/\S/.test(work_dir) || work_dir == null) {work_dir = "tmp_Biography"; window.SetProperty(" work directory", work_dir)};

//var work_path = fb.FoobarPath + clean(work_dir) + "\\";	
var work_path = fb.ProfilePath + clean(work_dir) + "\\";	
check_folder(work_path);
							
var script_path = work_path + "_download\\";							
check_folder(script_path);
if (!fso.FileExists(script_path + "download.vbs")) {create_download_file()};	

var doc = new ActiveXObject("htmlfile");								
var WshShell = new ActiveXObject("WScript.Shell");							
var vbs = "cscript //nologo \"" + script_path + "download.vbs\"";

var def_img;
//var def_img_set = false;
var def_img_on = window.GetProperty("default img", false);
var def_img_path_artist_review = window.GetProperty(" default img path bio", ".\\maybe\\textures\\nocover\\nocover.png"); 
var def_img_path_album_review = window.GetProperty(" default img path album review", ".\\maybe\\textures\\nocover\\nocover.png");
var def_img_transp = window.GetProperty(" default img transparence (0-255)", 255);
var def_img_fader = def_img_transp;
var no_def_img_msg_on = window.GetProperty("no def img msg on", true);

var def_img_artist_review = fso.FileExists(def_img_path_artist_review) ? resize_image(gdi.Image(def_img_path_artist_review)) : null;
var def_img_album_review = fso.FileExists(def_img_path_album_review) ? resize_image(gdi.Image(def_img_path_album_review)) : null;

var def_img_size;
def_img_ini();
var def_img_size_recount = false;

function def_img_ini() {
    if (def_img_cover_on){ 
        def_img = def_img_cover; 
        get_covers_info(0);
    }

    if (def_img_on){
        if (ch() == "album") {
            def_img = def_img_album_review;
        } else {
            def_img = def_img_artist_review;   
        }
    }

    def_img_size_recount = true;
}

var logo_img;
var logo_img_idx = window.GetProperty("logo_img_idx", 4);
var logo_img_transp = window.GetProperty(" logo img transparence (0-255)", 255);
var logo_fader = logo_img_transp;

load_lastFm_logo();

var logo_img_path = [
    script_path + "logo_1.png",					
    script_path + "logo_2.png",	 // not loaded
    script_path + "logo_3.png",
    script_path + "logo_4.png",
    script_path + "logo_5.png"
]

var logo_img_dim = [
    [37, 37, 0, 0],
    [40, 40, 0, 0],
    [60, 60, 0, 0],
    [70, 70, 0, 70],
    [60, 60, 0, 0]
]

logo_img_ini();

function logo_img_ini(){
    file = logo_img_path[logo_img_idx];
    i = logo_img_idx;
    logo_img = fso.FileExists(file) ? resize_logo_img(gdi.Image(file), logo_img_dim[i][0], logo_img_dim[i][1], logo_img_dim[i][2], logo_img_dim[i][3]) : null;   
}

function resize_logo_img(img, w, h, cx, cy){
    if (!img) return;

    var scale_w = w / img.Width;
    var scale_h = w / img.Height;
    
    var scale = Math.min(scale_w, scale_h);

    var iw = Math.round(img.Width * scale);
    var ih = Math.round(img.Height * scale)

    var temp_bmp = gdi.CreateImage(iw, ih);
    var temp_gr = temp_bmp.GetGraphics();
    temp_gr.SetSmoothingMode(2);
    temp_gr.SetInterpolationMode(7);
    temp_gr.DrawImage(img, 0, 0, iw, ih, cx, cy, img.Width, img.Height);
    temp_bmp.ReleaseGraphics(temp_gr);
    return temp_bmp;
    temp_bmp.Dispose();
    temp_gr = null;
    temp_bmp = null;
}

function def_fader_ini(){
    logo_fader = fade_effect ? 0 : logo_img_transp;
    def_img_fader = fade_effect ? 0 : def_img_transp;
}

var marvin_img_path = script_path + "marvin.png";
var marvin_img = fso.FileExists(marvin_img_path) ? resize_logo_img(gdi.Image(marvin_img_path), 100, 100, 0, 0) : null;

/*
function artist_folder_path(n) {
    if (!n) return;
    return work_path + n;
}
*/

var save_images = window.GetProperty("save images", true);
var save_images_to_artist_folder = window.GetProperty("save to artist folder containing track", false);

function artist_folder_path(n) {
    if (!n || !metadb) return "";
    
    if (metadb.RawPath.indexOf("file") < 0 || !save_images_to_artist_folder) {
        return work_path + n;
    }

    if (metadb.RawPath.indexOf("file") >= 0 && save_images_to_artist_folder) {
        var directory_path_arr = [], artist_path_arr = [], artist_path = "";
        directory_path_arr = directory_path.split("\\");
        
        for (var i = 0; i < directory_path_arr.length; i++) { 
            if (directory_path_arr[i].toLowerCase().replace(/\s*/g, "").match(n.toLowerCase().replace(/\s*/g, ""))){
                artist_path_arr = directory_path_arr.slice(0, i + 1);
                break;
            }
        }

        artist_path = artist_path_arr.join("\\");
        
        if (fso.FolderExists(artist_path)) {
            return artist_path + "\\" + "lastFm review";   
        } else {
            return work_path + n;
        }
    }     
}

function check_folder(n) {
    if (!n) return;
    try {
        if(!fso.FolderExists(n)) {fso.CreateFolder(n)};
    } catch(e) {}
}

function check_file(n) {
    if (!n) return;
    try {
        if (!fso.FileExists(n)) fso.CreateTextFile(n);	
    } catch(e) {}
}

function get_fnext(p) {
    if (!p) return "";
    return p.replace(/.*\\/g,'');
}

function get_dp(p) {
    if (!p) return "";
    return p.replace(/(.*)\\.*/g, '$1');
}

function get_fn(p) {
    if (!p) return "";
    return p.replace(/.*\\|\.[^.]+$/g, '')
}

var g_img = null;
var img_show = window.GetProperty("img show", true);
var img_below_text = window.GetProperty("img below text", true);
var img_size;
var img_size_recount = false;
var img_margin = window.GetProperty(" img: margin", 0);
var img_alignment = new Array("Adjust", "Adjust top - center", "Adjust top - left", "Centre", "Centre - top", "Stretch");
var img_alignment_idx = window.GetProperty("align mode", 1);
var img_selected = 0;
var img_file_names = [];
//var img_file_names_old = [];
//var img_refresh = true;
var images = [];
var no_img_msg = "";
var on_img = false;
//var no_text_msg = "";

var limit = window.GetProperty("img download limit", 6);

var img_border = window.GetProperty("img border", true);
var img_border_width = window.GetProperty(" img border width", 4);
if (!/\S/.test(img_border_width) || img_border_width <= 0) {img_border_width = 1; window.SetProperty(" img border width", img_border_width);}

var fader = 255;
var fade_effect = window.GetProperty("fade effect", false);

var quality_idx = window.GetProperty("download quality", 1);

var quality = [
    ["Low",     "avatar170s",   "avatar170s"],
    ["Medium",  "ar0",          "300x300"],
    ["High",    "770x0",        "770x0"] 
];

var data_main = window.GetProperty("data_main", 0); 
var data_sub = window.GetProperty("data_sub", 0);
var data_sub_value = [
//  menu text,                  LastFm query                    file name(tooltip, INI data)    data_sub
    ["Most popular albums",     "albums",                       "albums_popular"],              // 0
    ["Similar artists",         "similar",                      "similar"],                     // 1
    ["Album : ",                "",                             "album"],                       // 2
    ["Title : ",                "",                             "title"],                       // 3
    ["Lyrics : ",               "",                             "lyrics"]                       // 4
];

var scrollbar = window.GetProperty("Scrollbar", true);
var seekbar_x = 0;
var seekbar_y = 0;
var seekbar_w = window.GetProperty(" seekbar width ", 4);
var seekbar_h = 0;
var seekbar_h_min = 20;
var seekbar_k = 0;
var seekbar_posy = 0;
var on_seekbar = false;						
var on_seekbar_down = false;	
var on_scrollbar = false;						
var on_scrollbar_down = false;	

var scroll = scroll_ = scroll__ = scroll___ = scroll_old = 0;
var scroll_cut = 0;
var scroll_timer;
var scroll_timer_on = false;
var scroll_delta = 0;
var wheel_id = 0;
var key_down = false;
var scroll_k = window.GetProperty(" scroll k (0-5)", 1);
if (!/\S/.test(scroll_k) || scroll_k < 0 || scroll_k > 5) {scroll_k = 1; window.SetProperty(" scroll k(0-5)", scroll_k);}
						
var bg_transparence = window.GetProperty("text bg transparence (0-255)", 150);						
var t_margin = window.GetProperty(" text: margin", 10);						
var txt_x = window.GetProperty("txt_x", 0);						
var txt_y = window.GetProperty("txt_y", Math.round(window.Height / 2));	
var txt_x_old = txt_y_old = 0;
var delta_x, delta_y;						
var h0_y = h1_y = h2_y = t_y = t_x = 0;
var h1h2_y_delta = 10;	

var search_by = ["%album artist%", "%artist%", "%remixed by%"];
var search_by_idx = window.GetProperty("search by idx", 0);

var refresh_data = false;
var lock_loading = false;

var history = [];
var history_arr = [];
var history_seach = "";
var history_on = false;
var histity_list_edit = false;
var history_file_path = script_path + "history_list.txt";
var history_result = false;
var history_query = true;

var history_file_path_old = script_path + "history.txt"; // old version
if (fso.FileExists(history_file_path_old)){
    try {
        fso.MoveFile(history_file_path_old, history_file_path);  
    } catch(e) {};  
}

var path_old = complete_path = directory_path = "";
var tf_artist, meta_artist, artist_old;
var tf_album, meta_album, album_old;
var tf_title, meta_title, title_old;
var request_counter = 0;

var text = header_0 = header_1 = header_2 = "";
var text_hiden = window.GetProperty("txt hiden", false);
var cut = false;

var text_refresh_step = 2;
var text_arr = [];
var text_arr_tmp = [];
var text_height = 0;
var text_row_width = 0;
var text_row_height = 0;
var text_rows = 0;
var text_rows_per_panel = 0;
var text_rows_per_panel_height = 0;

var h0_text_arr = [];
var h0_text_row_height = 0;
var h0_text_rows_per_panel = 0;

var h1_char_width = 0;
var h1_text_arr = [];
var h1_text_row_height = 0;
var h1_text_rows_per_panel = 0;

var h2_text_arr = [];
var h2_text_row_height = 0;
var h2_text_rows_per_panel = 0;

var ci_x = 0;
var ci_y = 0;
var ci_y_old = 10;
var ci_text_arr = [];
var ci_text_row_width = 0;
var ci_text_height = 0;
var ci_text_row_height = 0;

var popular_this_week = "";
var latest_release = "";
var from_the_album = "";
var years_active = "";
var similar_artist = "";

var years_active_artist = window.GetProperty("years active artist", true);
var years_active_similar = window.GetProperty("years active similar", true);
var years_active_on = window.GetProperty("years active " + ch());

var info_text = [];
var info_text_old = "";
var info_text_arr = [];
var info_text_color = [];
var info_text_color_arr = [];
var info_text_font = [];
var info_text_font_arr = [];

var info_text_artist = window.GetProperty("info text artist", true);
var info_text_popular_albums = window.GetProperty("info text popular_albums", true);
var info_text_similar = window.GetProperty("info text similar", true);
var info_text_album = window.GetProperty("info text album", true);
var info_text_title = window.GetProperty("info text title", true);
var info_text_lyrics = window.GetProperty("info text lyrics", true);
var info_text_on = window.GetProperty("info text " + ch());

var on_text = false;
var on_header_0 = false;
var on_header_1 = false;
var on_header_2 = false;
var on_text_down = false;
var on_info_text_btn = false;
var on_years_active_btn = false;

var tooltip_on = false;
var tooltip_delay = window.GetProperty(" tooltip delay (ms)", 1000);
if (!/\S/.test(tooltip_delay) || tooltip_delay < 1){tooltip_delay = 1000; window.SetProperty(" tooltip delay (ms)", tooltip_delay)};
var tooltip = window.GetProperty("tooltip", false); 
var tooltip_text = "";
var pos_x = pos_y = x_old = y_old = 0;

var text_idx = 0;
var selected_item = "";
var selected_item_rows_idx = [];
var selected_item_rows = [];

var external_links = [];

var language_text = [
    ["en", "English",   "Text not found"],
    ["it", "Italian",   "Testo non trovato"],
    ["zh", "Chinese",   ". . ."],
    ["de", "German",    "Text nicht gefunden"],
    ["pl", "Polish",    "Nie znaleziono tekstu"],
    ["pt", "Portuguese",". . ."],
    ["ru", "Russian",   "  "],
    ["tr", "Turkish",   ". . ."],
    ["fr", "French",    "Texte non trouve"],
    ["sv", "Swedish",   ". . ."],
    ["ja", "Japanese",  ". . ."]
]

window.GetProperty("en", true);
window.GetProperty("it", false);
window.GetProperty("zh", false);
window.GetProperty("de", false);
window.GetProperty("pl", false);
window.GetProperty("pt", false);
window.GetProperty("ru", true);
window.GetProperty("tr", false);
window.GetProperty("fr", false);
window.GetProperty("sv", false);
window.GetProperty("ja", false);

var lang_idx = window.GetProperty("lang", 0);
var tmp_lang_idx;
var lang_arr = [];
create_lang_arr();

function create_lang_arr(){ 
    lang_arr = [];
    for (var i = 0; i < language_text.length; i++) {
        if (window.GetProperty(language_text[i][0]) == true){
            lang_arr.push(language_text[i][0]);
        }
    }
    
    if (lang_idx >= lang_arr.length) {
        lang_idx = lang_idx - 1 <= 0 ? 0 : lang_idx - 1; 
        window.SetProperty("lang", lang_idx);
    } 
    
    if (lang_idx < lang_arr.length) {
        var i = 0;
        do {
            if (tmp_lang_idx == lang_arr[i]) {
                lang_idx = i;
                window.SetProperty("lang", lang_idx);
            }  
            i++;
        } while (i < lang_arr.length);
    } 
    
    if (lang_arr.length == 1){
        tmp_lang = lang_arr[0];
    }
    
    if (lang_arr.length == 0){
        lang_arr.push(tmp_lang); 
        window.SetProperty(tmp_lang, true);
        get_text();
    }
}

function lang_query(i){
    return lang_arr[i] == "en" ? "" : lang_arr[i] + "/";;
}

function no_text_found(n) {
    tmp = "";
    var j = 0;
    do {
        if (language_text[j][0] == n) {
            tmp = language_text[j][2];
        }  
        j++;
    } while (j < language_text.length);
    return tmp;
}

function get_text_menu(n) {
    tmp = "";
    var j = 0;
    do {
        if (language_text[j][0] == n) {
            tmp = language_text[j][1];
        }  
        j++;
    } while (j < language_text.length);
    return tmp;
}

var cycle_txt_y = 20;
var cycle_set = false;
var cycle_timer, cycle_step = 0;
var cycle = window.GetProperty("auto cycle (sec)", 0);
if (cycle > 0) cycle_set_timer();

var delay = false;
var get_files_timer, ftimer, ftimer_logo, ftimer_def_img, tooltip_timer;

var def_img_cover_on = window.GetProperty("covers as default img", false);
var covers_on = window.GetProperty("covers on", false);
var covers_on_old = covers_on; 
var external = [];
var embedded = [];
var covers = [];
var attached_img_name = ["front cover", "back cover", "disc", "icon", "artist"];
var embedded_img_name = [];
var covers_title_old = covers_album_old = covers_directory_path_old = "";

var root_folders = ["cover", "scan", "art", "img", "images", "pic"]; 
var set_external = window.GetProperty("external", true);
var set_embedded = window.GetProperty("embedded", true);
var set_priority = window.GetProperty("set priority", 1);
var over_info_on = window.GetProperty("over info", true);

var covers_images = [];
var def_img_cover;

var panel_on = true;

var selection_mode = window.GetProperty("selection mode", 0);
var metadb;

on_item_focus_change();

function on_paint(gr){   
   !window.IsTransparent && gr.FillSolidRect(0, 0, ww, wh, bg_color);

    draw_image(gr); 
   
    if (!meta_artist && !history_on){
        text_shadow && gr.GdiDrawText( "No artist selected", gdi.Font("Arial",12, 0), bg_color, 0 + 1, 0 + 2, ww, wh, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_WORD_ELLIPSIS ); 
        gr.GdiDrawText( "No artist selected", gdi.Font("Arial",12, 0), h1_color, 0, 0, ww, wh, DT_SINGLELINE | DT_CENTER | DT_VCENTER | DT_WORD_ELLIPSIS ); 
    }

    if (cycle_set && on_img){   
        gr.FillSolidRect(0, 0, ww, wh, RGBA(getRed(bg_color), getGreen(bg_color), getBlue(bg_color), bg_transparence));   
        var txt_cycle = cycle == 0 ? "off" : cycle + " sec";   
        text_shadow && gr.GdiDrawText("auto cycle:   " + txt_cycle, t_font, bg_color, 0 + 1, cycle_txt_y + 2, ww, wh, DT_CENTER | DT_WORD_ELLIPSIS );
        gr.GdiDrawText("auto cycle:   " + txt_cycle, t_font, t_color, 0, cycle_txt_y, ww, wh, DT_CENTER | DT_WORD_ELLIPSIS );
    } else {  
        if (meta_artist || history_on) gr.FillSolidRect(txt_x, txt_y, ww - txt_x, wh - txt_y, RGBA(getRed(bg_color), getGreen(bg_color), getBlue(bg_color), bg_transparence)); 
    }  

    draw_seekbar(gr); 

    if (lock_loading){
        for (var i = 0; i < h0_text_rows_per_panel; i++){     // header_0
            try {
                color = on_header_0 || on_header_1 ? t_color : h1_color;
                
                text_shadow && gr.GdiDrawText( h0_text_arr[i], h0_font, bg_color, t_x + 1, h0_y + h0_text_row_height * i + 2, text_row_width, wh, text_alignment[text_alignment_h0][1] );   
                gr.GdiDrawText( h0_text_arr[i], h0_font, color, t_x, h0_y + h0_text_row_height * i, text_row_width, wh, text_alignment[text_alignment_h0][1] ); 
            } catch(e) {}
        }
    }

    for (var i = 0; i < h1_text_rows_per_panel; i++){     // header_1
        try {
            font = !history_on ? h1_font : (history_seach ? t_font : h0_font);
            color = history_on ? (history_seach ? (history_result ? color_true : (history_query ? t_color : color_error)) : h1_color) : h1_color;

            text_shadow && gr.GdiDrawText( h1_text_arr[i], font, bg_color, t_x + 1, h1_y + h1_text_row_height * i + 2, text_row_width, wh, text_alignment[text_alignment_h1][1] );   
            gr.GdiDrawText(h1_text_arr[i], font, color, t_x, h1_y + h1_text_row_height * i, text_row_width, wh, text_alignment[text_alignment_h1][1] ); 
        } catch(e) {}
    }

    if (h1_text_arr.length){
        l_x1 = t_x;
        l_y1 = h1_y + h1_text_row_height * h1_text_arr.length + h1h2_y_delta / 2;
        l_x2 = t_x + text_row_width;
        l_y2 = h1_y + h1_text_row_height * h1_text_arr.length + h1h2_y_delta / 2;
        l_color = RGBA(getRed(h1_color), getGreen(h1_color), getBlue(h1_color), 120);
        gr.DrawLine(l_x1, l_y1, l_x2, l_y2, 1, l_color);
        
        if (text_shadow){
            l_color_2 = RGBA(getRed(bg_color), getGreen(bg_color), getBlue(bg_color), 255);
            gr.DrawLine(l_x1, l_y1 + 1, l_x2, l_y2 + 1, 1, l_color_2);
        }
    }

    if (!history_on){
        if (on_info_text_btn && info_text.length) draw_info_text_btn(gr);
        if (on_years_active_btn && years_active) draw_years_active_btn(gr);
        
    }
        
    for (var i = 0; i < h2_text_rows_per_panel; i++){     // header_2
        try {
            color = ch() == "artist" || ch() == "similar" ? h1_color : h2_color;
            font = ch() == "artist" || ch() == "similar" ? t2_font : h2_font;
                
            text_shadow && gr.GdiDrawText( h2_text_arr[i], font, bg_color, t_x + 1, h2_y + h2_text_row_height * i + 2, text_row_width, wh, text_alignment[text_alignment_h2][1] );   
            gr.GdiDrawText( h2_text_arr[i], font, color, t_x, Math.round(h2_y + h2_text_row_height * i), text_row_width, wh, text_alignment[text_alignment_h2][1] ); 
        } catch(e) {}
    }

    for (var i = 0; i < text_arr.length; i += 2){    // text
        try {
            row = t_y + (i * text_row_height / 2) + scroll_;
            
            if (row > t_y - text_row_height && row < t_y + text_rows_per_panel_height){
                color = info_text_color_arr[i] ? info_text_color_arr[i] : t_color;
                font = info_text_font_arr[i] ? info_text_font_arr[i]:  t_font;

                var j = 0;
                do {
                    if (selected_item_rows_idx[j] == i / 2){
                        color = color_selected_item;
                    } 
                    j++;
                } while (j < selected_item_rows_idx.length); 

                if (row < t_y){
                    format = text_alignment[text_alignment_t][2];
                    dh = text_row_height - gr.CalcTextHeight(text_arr[i], font);
                    y = row + (text_row_height - scroll_delta) - dh;
                    h = text_row_height - (text_row_height - scroll_delta);
                } 
                
                if (row >= t_y && row <= t_y + text_rows_per_panel_height - text_row_height){
                    format = text_alignment[text_alignment_t][1];
                    y = row;
                    h = text_row_height;
                }
                
                if (row > t_y + text_rows_per_panel_height - text_row_height){
                    format = text_alignment[text_alignment_t][1];
                    y = row;
                    h = text_row_height - scroll_delta;
                } 
                
                text_shadow && gr.GdiDrawText( trim(text_arr[i]), font, bg_color, t_x + 1, y + 2, text_row_width, h, format );
                gr.GdiDrawText( trim(text_arr[i]), font, color, t_x, y, text_row_width, h, format );
            }
        } catch(e) {}
    }

    tooltip_on && draw_tooltip(gr);
}

function draw_image(gr){
    if (img_show){
        if (g_img){
            if (img_size_recount){
                img_size = calc_img_size(g_img);
                img_size_recount = false;
            }

            ci_y = img_size.y + img_size.h + img_border_width + ci_text_row_height / 2;
            ci_x = t_margin;

            gr.DrawImage(g_img, img_size.x, img_size.y, img_size.w, img_size.h, img_size.cx, img_size.cy, img_size.cw, img_size.ch, 0, fader);
            if (img_size.w || img_size.h){
                img_border && gr.DrawRect(img_size.x - img_border_width /2, img_size.y - img_border_width /2, img_size.w + img_border_width, img_size.h + img_border_width, img_border_width, RGBA(getRed(t_color), getGreen(t_color), getBlue(t_color), fader)); 
                lw = 1;
                img_border && gr.DrawRect(img_size.x + lw / 2, img_size.y + lw / 2, img_size.w - lw, img_size.h - lw, lw, RGBA(getRed(bg_color), getGreen(bg_color), getBlue(bg_color), fader - 200 <= 0 ? 0 : fader - 200));
            }
        }
        
        if (!g_img){
            ci_y = t_margin;
            ci_x = t_margin;
        }

        if (!g_img){
            if (logo_img){
                if (!def_img_on && !def_img_cover_on){
                    if (logo_fader == 0 && fade_effect) fader_timer_logo();
                    gr.DrawImage(logo_img, 5, 5, logo_img.Width, logo_img.Height, 0, 0, logo_img.Width, logo_img.Height, 0, logo_fader);          
                
                    ci_y = 5 + logo_img.Height + ci_text_row_height;;
                    ci_x = 5;
                }
            }
        
            if (def_img){
                if (def_img_on || def_img_cover_on){ 
                    if (def_img_size_recount){
                        def_img_size = calc_img_size(def_img);
                        def_img_size_recount = false;
                    }

                    ci_y = def_img_size.h + img_border_width + ci_text_row_height / 2;
                    ci_x = t_margin;

                    if (def_img_fader == 0 && fade_effect) fader_timer_def_img();
                    gr.DrawImage(def_img, def_img_size.x, def_img_size.y, def_img_size.w, def_img_size.h, def_img_size.cx, def_img_size.cy, def_img_size.cw, def_img_size.ch, 0, def_img_fader);
                    img_border && gr.DrawRect( def_img_size.x - img_border_width /2, def_img_size.y - img_border_width /2, def_img_size.w + img_border_width, def_img_size.h + img_border_width,  img_border_width, RGBA(getRed(t_color), getGreen(t_color), getBlue(t_color), def_img_fader));
                }
            }
            
            if (!def_img && def_img_on && !covers_on && no_def_img_msg_on){
                ci_y = t_margin;
                ci_x = t_margin;
                text_shadow && gr.GdiDrawText("no default amage", t2_font, bg_color, ci_x + 1, ci_y + 1, ww, wh, text_alignment[text_alignment_t][1] ); 
                gr.GdiDrawText("no default amage", t2_font, h1_color, ci_x, ci_y, ww, wh, text_alignment[text_alignment_t][1] ); 
            }
        }
        
        if (over_info_on){
            if ((!g_img && def_img_cover_on) || covers_on){
                if (Math.abs(ci_y - ci_y_old) < text_row_height / 2){
                    ci_y = ci_y_old;
                } else {
                    ci_y_old = ci_y;
                }
   
                for (var i = 0; i < ci_text_arr.length; i++){ 
                    text_shadow && gr.GdiDrawText(ci_text_arr[i], ci_font, bg_color, ci_x + 1, ci_y + ci_text_row_height * i + 1, ci_text_row_width, wh, text_alignment[text_alignment_ci][1] ); 
                    gr.GdiDrawText(ci_text_arr[i], ci_font, h1_color, ci_x, ci_y + ci_text_row_height * i, ci_text_row_width, wh, text_alignment[text_alignment_ci][1] ); 
                }
            }
        }
    }
}

function draw_seekbar(gr){
    seekbar_x = (text_height > text_rows_per_panel_height && scrollbar) ? ww - t_margin - seekbar_w - 10 : ww;
    seekbar_h = text_rows_per_panel_height * (text_rows_per_panel / text_rows);

    var seekbar_h_d = 0;

    if (seekbar_h < seekbar_h_min && text_rows_per_panel_height > 0){
        seekbar_h_d = seekbar_h_min - seekbar_h;
        seekbar_h = seekbar_h_min;
    } 
        
    seekbar_k = (text_rows_per_panel_height - seekbar_h_d) / text_rows;
    seekbar_y = t_y + (scroll_ * -1) / text_row_height * seekbar_k;
    
    if (scrollbar && text_height > text_rows_per_panel_height){
        gr.SetSmoothingMode(2);
        
        seekbar_alpha = (on_seekbar || on_seekbar_down || on_scrollbar) && !on_text_down ? 255 : 100;
        seekbar_color = RGBA(getRed(h1_color), getGreen(h1_color), getBlue(h1_color), seekbar_alpha);
        gr.FillSolidRect(seekbar_x + 10, seekbar_y, seekbar_w, seekbar_h, seekbar_color);
    }  
}  

function draw_info_text_btn(gr){
    var x = t_x + text_row_width / 2;
    var y = t_y - text_row_height / 2;
    var arrow_direction = info_text_on ? 0 : 1;
    var draw = text_rows_per_panel > 0 ? true : false;
    draw_triangle(gr, x, y, arrow_direction, draw);
}

function draw_years_active_btn(gr){
    var x = t_x + text_row_width / 2;
    var y = h1_y + h1_text_row_height * h1_text_arr.length + h1h2_y_delta / 2;
    var arrow_direction = years_active_on ? 0 : 1;
    var draw = h2_text_rows_per_panel > 0 ? true : false;
    draw_triangle(gr, x, y, arrow_direction, draw);
}

function draw_triangle(gr, x, y, arrow_direction, draw){
    var d = 9;
    var radius = d / 2;
    var points = [], points_bg = [];
    var steps = 6;

    for (var i = 0; i < steps; i++) {
        if (i % 2 == arrow_direction) {
            points.push(x + (radius * Math.cos(Math.PI * i / steps * 2 - Math.PI / 2)));
            points.push(y - 1 + (radius * Math.sin(Math.PI * i / steps * 2 - Math.PI / 2)));
            points_bg.push(x + (radius * Math.cos(Math.PI * i / steps * 2 - Math.PI / 2))+1);
            points_bg.push(y - 1 + (radius * Math.sin(Math.PI * i / steps * 2 - Math.PI / 2))+1);
        }
    }
     
    gr.SetSmoothingMode(4);
    if (draw){
        text_shadow && gr.FillPolygon(bg_color, 1, points_bg);
        gr.FillPolygon(h1_color, 1, points);
    }  
}

function draw_tooltip(gr){
    if (!tooltip_text) return;
    
    tt_w = gr.CalcTextWidth(tooltip_text, tt_font) + 14;
    tt_h = gr.CalcTextHeight(tooltip_text, tt_font) + 2;
    tt_x = pos_x - tt_w * 0.5;
    tt_x = tt_x <= 10 ? 10 : (tt_x >= ww - tt_w - 10 ? ww - tt_w - 10 : tt_x);
    tt_y = pos_y - tt_h - 8;
    tt_y = tt_y <= 10 ? 10 : tt_y;

    gr.FillSolidRect(tt_x, tt_y, tt_w, tt_h, t_color);
    gr.DrawRect(tt_x, tt_y, tt_w, tt_h, 1, bg_color);
    gr.GdiDrawText( tooltip_text, tt_font, bg_color, tt_x, tt_y, tt_w, tt_h, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
}

function on_playlist_switch() {
    on_item_focus_change();
}

function on_playback_new_track() {
    on_item_focus_change();
}

function on_playback_dynamic_info_track() {
    on_item_focus_change();
}

function on_playback_stop() {
    on_item_focus_change();
}

function on_selection_changed(metadb) { // 
   on_item_focus_change();
}

function on_item_focus_change() {
    switch (selection_mode) {
    case 0:
		metadb = fb.IsPlaying ? fb.GetNowPlaying() : fb.GetFocusItem();  
        break;  
    case 1:   
		metadb = fb.GetFocusItem();
        break;   
    } 
    if (metadb) on_metadb_changed();  
}   

function Eval(field) {  
    if (!metadb) return "";  
    complete_path = metadb.Path;
    directory_path = fb.Titleformat("$directory_path(%path%)").EvalWithMetadb(metadb);
	
	var tfo = fb.TitleFormat("[" + field + "]");
	
	if (fb.IsPlaying && complete_path.indexOf('://') > 0) {
		return tfo.Eval();
	} else {
		return tfo.EvalWithMetadb(metadb);
	}
}

function on_metadb_changed(handles, fromhook) {
    if (!panel_on) return; 
    if (!metadb) return;
    
    ini_data();
    
    if (directory_path.indexOf("://") >= 0 && covers_on) {
        covers_on_old = covers_on;
        covers_on = false;
    }
    
    if (directory_path.indexOf("://") < 0 ) {
        covers_on = covers_on_old;
    }
    
    var path = artist_folder_path(clean(meta_artist));

    if (refresh_data){
        del_folder(path);///
        artist_old = album_old = title_old = "";
        clear_covers_var();
        refresh_data = false;
    }
    
    if ((meta_artist && (meta_artist != artist_old)) || refresh_data){
        add_name_to_history_list(meta_artist);
        
        del_empty_folders();
        
        check_folder(path);///
        
        //if (!save_images) !lock_loading && del_folders(clean(meta_artist));	
        
        if (!save_images) {
            if (!save_images_to_artist_folder){
                !lock_loading && del_folders(clean(meta_artist));
            }
            
            if (save_images_to_artist_folder){
                del_folder(path_old);
            }
        }
        
        path_old = path;///
    }

    if ((meta_artist != artist_old) && (ch() == "artist" || ch() == "popular_albums" || ch() == "similar")){
        get_img(meta_artist, meta_album, meta_title);
        artist_old = meta_artist;
    }

    if ((meta_album != album_old) && ch() == "album"){
        get_img(meta_artist, meta_album, meta_title);
        album_old = meta_album;
    }

    if ((meta_title != title_old) && (ch() == "title" || ch() == "lyrics")){
        get_img(meta_artist, meta_album, meta_title);
        title_old = meta_title;
    }

    try {
        if (lock_loading && selected_item){
            var items = fb.GetLibraryItems();
            items.OrderByPath();
            complete_path = "";
            directory_path = "";
            for (var i = 0; i < items.Count; i++) {    
                if (items.Item(i).Path.toLowerCase().indexOf(clean(selected_item).toLowerCase()) >= 0){
                //if (get_dp(items.Item(i).Path).toLowerCase().indexOf(clean(selected_item).toLowerCase()) >= 0){
                    complete_path = items.Item(i).Path;
                    directory_path = get_dp(items.Item(i).Path);
                    break;
                }
            }
        }
    } catch(e) {}
        
    if (directory_path != covers_directory_path_old || tf_title != covers_title_old) {
        get_embedded_covers(complete_path);
    }
            
    if (directory_path != covers_directory_path_old || tf_album != covers_album_old){
        get_external_covers(directory_path, tf_artist, tf_album);
    }

    if (directory_path != covers_directory_path_old || tf_album != covers_album_old || tf_title != covers_title_old){
        get_covers();
        covers_title_old = tf_title;
        covers_album_old = tf_album;
        covers_directory_path_old = directory_path;
    } 
} 

function ini_data(){
    if (!lock_loading){
        search = search_by_idx == 2 ? "$if3(%remixed by%, %album artist%, %artist%)" : search_by[search_by_idx];
        tf_artist = Eval(search);
        tf_album = Eval('%album%');
        tf_title = Eval('%title%');
    }
        
    meta_artist = remap_artist(tf_artist);
    meta_album = remap_album(remap_artist(tf_artist), tf_album);
    meta_title = tf_title;
    
    if (!meta_album && ch() == "album" || !meta_title && (ch() == "title" || ch() == "lyrics")) {
        data_main = 0;
    }  
}

function clear_img_var() {
    if (covers_on) return;
    img_selected = 0;
    images = [];
    img_file_names = []; 
    no_img_msg = "";
    g_img = null;
}

function clear_covers_var() {
    covers_title_old = covers_album_old = covers_directory_path_old = ""; 
    external = [];
    embedded = [];
    covers = [];
    ci_text_arr = [];
    def_img_cover = null;
    def_img_ini();
    g_img = null;
}

function get_img(artist, album, title) {
    path = artist_folder_path(clean(artist));

    clear_img_var();
    clear_txt_var();

    if (fso.FolderExists(path)){
        get_img_from_dir(path, artist, album, title);

        if (images.length) {
            !covers_on && next_image_lastFm(0); 
            get_text(path, artist, album, title);
        } else {  
            switch(ch()) {                                                                                       
            case "artist":  
                get_lastFm_meta_artist_img(true, path, artist);
                break;              
            case "popular_albums":                                                                                
                get_lastFm_popular_albums_img(true, path, artist);
                break;              
            case "similar":  
                get_lastFm_similar_img(true, path, artist);
                break;
            case "album": 
                get_lastFm_meta_album_img(true, path, artist, album);
                break;    
            case "title":
            case "lyrics":
                get_lastFm_meta_title_img(true, path, artist, album, title);
                break;
            }  
        }
    }                                                                                        
}

function get_img_from_dir(path, artist, album, title) {
    artist = artist ? clean(artist) : "";
    album = album ? clean(album) : "";
    title = title ? clean(title) : ""; 

    switch(ch()) {                                                                                       
    case "artist":  
        img_file_names = naturalSort(utils.Glob( path + "\\" + artist + "*" + "artist.jpg").toArray());
        break;              
    case "popular_albums":                                                                                
        img_file_names = [];  
        var j = 0;
        do {
            var album = utils.ReadINI( path + "\\" + artist + "_album_info.ini", data_sub_value[data_sub][2] + " : name" , j );                                                               
            album && img_file_names.push(path + "\\" + artist + "_" + clean(album) + ".jpg")
            j++;
        } while (j < limit); 
        break;              
    case "similar":  
        img_file_names = naturalSort(utils.Glob( path + "\\" + artist + "*" + data_sub_value[data_sub][2] + ".jpg").toArray());
        break;
    case "album": 
        img_file_names = utils.Glob( path + "\\" + artist + "_" + album.replace(/[.']/g, "*") + ".jpg").toArray();
        break;    
    case "title":
    case "lyrics":
        var album = utils.ReadINI( path + "\\" + artist + "_title_info.ini", clean_ini(title), "album");
        img_file_names = utils.Glob( path + "\\" + artist + "_" + clean(album) + ".jpg").toArray(); 
        break;
    } 
    
    images = [];

    var i = 0;
    do {
        var tmp;
        if (fso.FileExists(img_file_names[i])){
            images.push(img_to_object(img_file_names[i]));
        }
        i++;
    } while (i < img_file_names.length);
    
    if (images.length == 0) def_img_ini();
    if (cycle_timer) cycle_step = 0;
}

function next_image_lastFm(d){
    fader = fade_effect ? 0 : 255;
    def_fader_ini();
    
    if (d < 0) {img_selected = img_selected <= 0 ? images.length - 1 : img_selected = img_selected - 1};
    if (d > 0) {img_selected = img_selected >= images.length - 1 ? 0 : img_selected = img_selected + 1};

    g_img = images[img_selected];
    if (g_img) img_size_recount = true;

    window.Repaint();
    if (g_img && fade_effect) fader_timer();
}

function resize_image(img){
    if (!img || !ww || !wh) return;
    
    var scale_w = ww / img.Width;
    var scale_h = wh / img.Height;
    
    if (img_alignment_idx == 0 || img_alignment_idx == 1 || img_alignment_idx == 2){
        var scale = Math.min(scale_w, scale_h);
    } else {
        var scale = Math.max(scale_w, scale_h);
    }

    var iw = Math.round(img.Width * scale);
    var ih = Math.round(img.Height * scale)

    return img.Resize(iw, ih, 7);
    img && img.Dispose();
    img = null;
}

function clear_txt_var() {
    similar_artist = "";
    years_active = "";
    info_text = [];
    info_text_color = [];
    info_text_font = [];
    popular_this_week = "";
    latest_release = "";
    from_the_album = "";
    external_links = [];
    history = [];
    selected_item_rows_idx = [];
    scroll = scroll_ = scroll__ = scroll___ = 0;
    header_1 = "";
    header_2 = "";
    text = "";
    get_text_arr(true);
}

function get_text(path, artist, album, title){
    clear_txt_var();
    
    switch(ch()) {                                                                                       
    case "artist":  
        get_bio_text(path, artist);
        break;              
    case "popular_albums":                                                                                
        get_popular_albums_text(img_selected, path, artist);
        break;              
    case "similar":  
        get_similar_text(img_selected, path, artist);
        break;
    case "album": 
        get_meta_album_text(path, artist, album);
        break;    
    case "title":
        get_meta_title_text(path, artist, album, title);
        break; 
    case "lyrics":
        get_meta_lyrics_text(path, artist, album, title);
        break;
    }      

    get_external_links(path, artist); 
}

function get_bio_text(path, artist) {
    var file = path + "\\" + clean(artist) + "_biography_" + lang_arr[lang_idx] + ".txt";
    years_active = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)) + " : years active", lang_arr[lang_idx]).replace(/\*/gi, "\n").replace(/\*/gi, "\n"); 
    popular_this_week = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), "popular_this_week");
    latest_release = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), "latest_release");

    info_text = get_info_text("", path, artist, "", "");
    info_text_color = get_info_text_color("", path, artist, "", "");
    info_text_font = get_info_text_font("", path, artist, "", "");

    if (!info_text.length && request_counter <= 1) {
        get_lastFm_artist_info_text(path, "file", artist);
    } else {
        if (fso.FileExists(file)){
            read_txt_file(file);
        } else {
            get_lastFm_bio_text(path, file, artist);
        }				
        request_counter = 0;
    }
    request_counter++;
}

function get_popular_albums_text(s, path, artist){
    var album = utils.ReadINI( path + "\\" + clean(artist) + "_album_info.ini", data_sub_value[data_sub][2] + " : name" , s );				
    var file = path + "\\" + clean(artist) + "_" + clean(album) + "_" + lang_arr[lang_idx] + ".txt";   
    
    header_2 = album;	

    info_text = get_info_text("", path, artist, album, "");
    info_text_color = get_info_text_color("", path, artist, album, "");
    info_text_font = get_info_text_font("", path, artist, album, "");

    if (!info_text.length && request_counter <= 1) {
        get_lastFm_meta_album_img(false, path, artist, album);
    } else {
        if (fso.FileExists(file)){			
            read_txt_file(file);			
        } else {	
            get_lastFm_album_text(path, file, album ? artist : "", album);
        }
        request_counter = 0;        
    }
    request_counter++;
}

function get_meta_album_text(path, artist, album) {	
    var file = path + "\\" + clean(artist) + "_" + clean(album) + "_" + lang_arr[lang_idx] + ".txt";   
       
    header_2 = album;	

    info_text = get_info_text("", path, artist, album, "");
    info_text_color = get_info_text_color("", path, artist, album, "");
    info_text_font = get_info_text_font("", path, artist, album, "");

    if (!info_text.length && request_counter <= 1) {
        get_lastFm_meta_album_img(false, path, artist, album);
    } else {			
        if (fso.FileExists(file)){			
            read_txt_file(file);			
        } else {
            get_lastFm_album_text(path, file, artist, album);
        }	
        request_counter = 0;    		
    }
    request_counter++;
}

function get_similar_text(s, path, artist) {
    var file = path + "\\" + clean(artist) + "_" + s + "_" +  data_sub_value[data_sub][2] + "_" + lang_arr[lang_idx] + ".txt";   
    similar_artist = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", data_sub_value[data_sub][2] + " : name" , s );  
    years_active = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(similar_artist)) + " : years active", lang_arr[lang_idx]).replace(/\*/gi, "\n") ; 

    if (!similar_artist && request_counter <= 1) {
        get_lastFm_similar_img(path, artist);
    } else {
        if (fso.FileExists(file)){
            read_txt_file(file);
        } else {
            get_lastFm_bio_text(path, file, similar_artist);  
        }
        request_counter = 0;  
    }
    request_counter++;
}

function get_meta_title_text(path, artist, album, title) {	
    var file = path + "\\" + "title_" + clean(title) + "_" + lang_arr[lang_idx] + ".txt";   				
    
    header_2 = title;
			
    info_text = get_info_text("", path, artist, album, title);
    info_text_color = get_info_text_color("", path, artist, album, title);
    info_text_font = get_info_text_font("", path, artist, album, title);
    
    from_the_album = utils.ReadINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "album");
		
    if (!info_text.length && request_counter <= 1) {	
        get_lastFm_meta_title_img(false, path, artist, "", title);
    } else {			
        if (fso.FileExists(file)){			
            read_txt_file(file);			
        } else {			
            get_lastFm_meta_title_text(path, file, artist, album, title);
        }	
        request_counter = 0;    		
    }
    request_counter++;
}

function get_meta_lyrics_text(path, artist, album, title) {	
    var file = path + "\\" + "lyrics_" + clean(title) + ".txt";   				

    header_2 = title;

    info_text = get_info_text("", path, artist, album, title);
    info_text_color = get_info_text_color("", path, artist, album, title);
    info_text_font = get_info_text_font("", path, artist, album, title);

    if (fso.FileExists(file)){	
        read_txt_file(file);			
    } else {
        get_metrolyrics_meta_lyrics_text(path, file, artist, title);
    }	
}

function get_info_text(s, path, artist, album, title) {
    switch(ch()) {                                                                                       
    case "artist":  
        var text_rank = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_rank");  
        var text = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx]); 
        break;              
    case "popular_albums":                                                                                
    case "album": 
        var text = utils.ReadINI( path + "\\" + clean(artist) + "_album_info.ini", clean_ini(clean(album)), lang_arr[lang_idx]); 
        break;    
    case "title":
        var text = utils.ReadINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), lang_arr[lang_idx]); 
        break; 
    case "lyrics":
        var text = utils.ReadINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "lyrics");  
        break;
    }   

    text = text_rank ? text_rank + text : text;
    return (text ? text.replace(/\*+$/g, "").split("*") : []); 
}

function get_info_text_color(s, path, artist, album, title) {
    switch(ch()) {                                                                                       
    case "artist":  
        var color_rank = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_rank_c"); 
        var color = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_c"); 
        break;            
    case "popular_albums":                                                                                
    case "album": 
        var color = utils.ReadINI( path + "\\" + clean(artist) + "_album_info.ini", clean_ini(clean(album)), lang_arr[lang_idx] + "_c");  
        break;  
    case "title":
        var color = utils.ReadINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), lang_arr[lang_idx] + "_c");  
        break;
    case "lyrics":
        var color = utils.ReadINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "lyrics_c");  
        break;
    }   

    color = color_rank ? color_rank + color : color;
    return (color ? color.replace(/\*+$/g, "").split("*") : []);
}

function get_info_text_font(s, path, artist, album, title) {
    switch(ch()) {                                                                                       
    case "artist":  
        var font_rank = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_rank_f"); 
        var font = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_f"); 
        break;             
    case "popular_albums":                                                                                
    case "album": 
        var font = utils.ReadINI( path + "\\" + clean(artist) + "_album_info.ini", clean_ini(clean(album)), lang_arr[lang_idx] + "_f");  
        break;
    case "title":
        var font = utils.ReadINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), lang_arr[lang_idx] + "_f");  
        break;
    case "lyrics":
        var font = utils.ReadINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "lyrics_f");  
        break;
    }  

    font = font_rank ? font_rank + font : font;
    return (font ? font.replace(/\*+$/g, "").split("*") : []); 
}

function get_external_links(path, artist) {
    var info_external_links = utils.ReadINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(artist), "external_links");
    external_links = info_external_links ? info_external_links.split("*") : []; 

    if (!external_links.length) get_artist_external_links(path, artist);
}

function read_txt_file(file){
    if (!file) return; 
    text = utils.ReadTextFile(file);
    get_text_arr(true);
}

function get_text_arr(refresh_text) {
    t_x = txt_x + t_margin;

    text_row_width = scrollbar ? Math.max(ww - t_x - t_margin - seekbar_w - 10, 0) : Math.max(ww - t_x - t_margin, 0);

    temp_bmp = gdi.CreateImage(1, 1);
    temp_gr = temp_bmp.GetGraphics();

    header_0 = lock_loading ? "l o c k" : "";
    h0_text_row_height = temp_gr.CalcTextHeight("Header_0", h0_font);
    var h0_text_arr_tmp = header_0 ? temp_gr.EstimateLineWrap(header_0, h0_font, text_row_width).toArray() : []; 


    if (!history_on){
        header_1 = ch() == "similar" ? similar_artist : meta_artist;
    }
    
    if (history_on){
        header_1 = history_seach ? title_case(history_seach) : "enter char (Ctrl-V, BS or Esc)";
    }
    
    h1_char_width = temp_gr.CalcTextWidth(header_1.substr(0, 1), h1_font);
    
    font = !history_on ? h1_font : t_font;
    h1_text_row_height = temp_gr.CalcTextHeight("Header_1", font);
    var h1_text_arr_tmp = header_1 ? temp_gr.EstimateLineWrap(header_1, font, text_row_width).toArray() : [];


    if (!history_on){
        if (ch() == "artist" || ch() == "similar"){
            years_active_on = window.GetProperty("years active " + ch());
            header_2 = years_active_on ? years_active : "";
        }
    }

    if (history_on){
        header_2 = ""; 
    }

    var font = ch() == "artist" || ch() == "similar" ? t2_font : h2_font;
    h2_text_row_height = temp_gr.CalcTextHeight("Header_2", font);
    var h2_text_arr_tmp = header_2 ? temp_gr.EstimateLineWrap(header_2, font, text_row_width).toArray() : [];
    
    text_row_height = temp_gr.CalcTextHeight("Biography", t_font);

    info_text_on = window.GetProperty("info text " + ch());

    if (Math.abs(txt_x - txt_x_old) > text_refresh_step || refresh_text){
        info_text_arr = [];
        info_text_color_arr = [];
        info_text_font_arr = [];
        
        selected_item_rows = [];

        if (!history_on && info_text_on && info_text.length){
            for (var i = 0; i < info_text.length; i++) {
                var color;
                var font;
            
                if (info_text_color[i] == "h1_color") color = h1_color;
                if (info_text_color[i] == "t_color") color = t_color;
            
                if (info_text_font[i] == "t2_font") font = t2_font;
                if (info_text_font[i] == "t_font") font = t_font;

                var tmp_arr = temp_gr.EstimateLineWrap( info_text[i], font, text_row_width).toArray();
                info_text_arr = info_text_arr.concat(tmp_arr);

                for (var j = 0; j < tmp_arr.length; j++) {
                    info_text_color_arr.push(color);
                    info_text_font_arr.push(font);
                    
                    if (j % 2){
                        if ( info_text[i] == popular_this_week || info_text[i] == latest_release || info_text[i] == from_the_album){
                            selected_item_rows.push(info_text[i]);
                        } else  {
                            selected_item_rows.push("");
                        }
                    }
                }
            }
            info_text_arr.push("\n", 0);
        }
        history_arr = [];

        if (history_on && history.length){
            for (var i = 0; i < history.length; i++) {

                var tmp_arr = temp_gr.EstimateLineWrap( history[i], t_font, text_row_width).toArray();
                history_arr = history_arr.concat(tmp_arr);

                for (var j = 0; j < tmp_arr.length; j++) {
                    if (j % 2){
                        selected_item_rows.push(history[i]);
                    }
                }
            }
        }
        text_arr_tmp = [];

        var t = !history_on ? text : "";
        if (t) text_arr_tmp = temp_gr.EstimateLineWrap(t, t_font, text_row_width).toArray();
        
        text_arr = [];
        text_arr = text_arr.concat(history_on ? history_arr : info_text_arr, text_arr_tmp);

        txt_x_old = txt_x;
        refresh_text = false;
    }

    temp_bmp.ReleaseGraphics(temp_gr);
    temp_bmp.Dispose();
    temp_gr = null;
    temp_bmp = null;
    CollectGarbage();
    
    h0_y = Math.round(txt_y) + t_margin;
    var h0_text_panel_height = Math.floor(Math.max(0, window.Height - t_margin - h0_y));
    h0_text_rows_per_panel = Math.max(1, Math.floor(h0_text_panel_height / h0_text_row_height));

    h0_text_arr = [];
    for (var i = 0; i < h0_text_arr_tmp.length; i += 2) {
        h0_text_arr.push(trim(h0_text_arr_tmp[i]));
    }

    h1_y = h0_y + h0_text_arr.length * h0_text_row_height;
    var h1_text_panel_height = Math.floor(Math.max(0, window.Height - t_margin - h1_y));
    h1_text_rows_per_panel = Math.max(1, Math.floor(h1_text_panel_height / h1_text_row_height));

    h1_text_arr = [];
    for (var i = 0; i < h1_text_arr_tmp.length; i += 2) {
        h1_text_arr.push(trim(h1_text_arr_tmp[i]));
    }

    h2_y = h1_y + h1_text_arr.length * h1_text_row_height + h1h2_y_delta;
    var h2_text_panel_height = Math.floor(Math.max(0, window.Height - t_margin - h2_y));
    h2_text_rows_per_panel = Math.floor(h2_text_panel_height / h2_text_row_height);

    h2_text_arr = [];
    for (var i = 0; i < h2_text_arr_tmp.length; i += 2) {
        h2_text_arr.push(trim(h2_text_arr_tmp[i]));
    }

    t_y = h2_y + h2_text_arr.length * h2_text_row_height + text_row_height;
    text_rows = text_arr.length / 2;
    text_height = text_rows * text_row_height;

    var text_panel_height = Math.floor(Math.max(0, window.Height - t_margin - t_y));
    
    text_rows_per_panel = Math.floor(text_panel_height / text_row_height);
    text_rows_per_panel_height = text_rows_per_panel * text_row_height;

    if (text_rows_per_panel_height + Math.abs(scroll) > text_height && scroll < 0) {   
        scroll = scroll_ = scroll__ = scroll___ = (text_height - text_rows_per_panel_height) * -1;
    }
        
    if (scroll % text_row_height){  // if font size changed
        scroll = scroll_ = scroll__ = scroll___ = Math.ceil(scroll / text_row_height) * text_row_height;
    } 
    
    window.Repaint();
}

function strip_tags(t) {
    doc.open();
    var div = doc.createElement("div");
    div.innerHTML = t.replace(/<[Pp][^>]*>/g, "").replace(/<\/[Pp]>/g, "<br>").replace(/\n/g, "<br>");
    var text = div.innerText;
    doc.close();
    return text.replace(/^\s+|\s+$/g, "");
}

function save_txt_file(t, file){
    if (!t || !meta_artist) return; 
    if (fso.FolderExists(artist_folder_path(clean(meta_artist)))){
        try {
            file = fso.OpenTextFile( file, 2, true, -1)
            file.Write(t);
            file.Close();
        } catch(e) {
            return;
        }
    }
}

var menu_items = [
    "Selected languages",
    "Selection mode",
    "Image source",
    "last.fm",
    "External links",
    "Refresh",
    "History",
    "Remap",
    "Search by",
    "Text",
    "Image",
    "Copy to folder containing track",
    "Storage",
    "Language selection",
    "Help",
    "Properties",
    "Configure"
];

function main_menu_setting(x, y){
    for (var i = 0; i < menu_items.length; i++) {
        window.GetProperty("mi_" + menu_items[i], false);
    }
    
    var _menu_s = window.CreatePopupMenu();

    for (var i = 1; i < menu_items.length + 1; i++) {
        _menu_s.AppendMenuItem( MF_ENABLED, i, menu_items[i - 1]);   
        _menu_s.CheckMenuItem(i - 0, window.GetProperty("mi_" + menu_items[i - 1]));
    }
    
    _menu_s.AppendMenuItem( MF_SEPARATOR, 0, 0); 
    _menu_s.AppendMenuItem( MF_ENABLED, 100, "Return to main menu"); 

    ret_s = _menu_s.TrackPopupMenu(x, y);

    switch (true) {
    case (ret_s >= 1 && ret_s <= menu_items.length + 1):
        selected_item = window.GetProperty("mi_" + menu_items[ret_s - 1]);
        window.SetProperty("mi_" + menu_items[ret_s - 1], selected_item == false ? true : false);
        main_menu_setting(x, y);
        break;
    }
    
    switch (ret_s) {
    case 100:
        on_mouse_rbtn_up (x, y);
        break;
    }
    _menu_s.Dispose();
}

function mi_prop(item){
    return  window.GetProperty("mi_" + item) ? true : false;
}

function mi_dim(t1, t2) {
    w = 35;
    return (t1 + t2).length > w ? (t1 + t2).substr(0, w - 3) + "..." : t1 + t2; 
}

function on_mouse_rbtn_up (x, y){   
    var _menu = window.CreatePopupMenu();
    var _group_20 = window.CreatePopupMenu();
    
    function mi(item){
        return  window.GetProperty("mi_" + item) ? _menu : _group_20;
    }
    
    function EMI(n1, v1, n2, v2){
        return n1 == v1 && n2 == v2 ? MF_GRAYED : MF_ENABLED;
    }

    for (var i = 1; i < lang_arr.length + 1; i++) {
        menuItem = get_text_menu(lang_arr[i - 1]);
        mi("Selected languages").AppendMenuItem( EMI(window.GetProperty("lang") + 1, i), i, menuItem);  
        mi("Selected languages").CheckMenuRadioItem(i, lang_arr.length + 1, window.GetProperty("lang") + 1); 
        //try { 
        //    mi("Selected languages").EnableMenuItem(window.GetProperty("lang") + 1, 1);
        //} catch(e){};
    }
    
    mi("Selected languages").AppendMenuItem( MF_SEPARATOR, 0, 0); 

    var _group_selection_mode = window.CreatePopupMenu();
        _group_selection_mode.AppendTo(mi("Selection mode"), MF_ENABLED, "Selection mode");

        _group_selection_mode.AppendMenuItem( EMI(selection_mode, 0), 40, "Prefer now playing");   
        _group_selection_mode.AppendMenuItem( EMI(selection_mode, 1), 41, "Follow selected track");   
        _group_selection_mode.CheckMenuRadioItem(40, 41 , selection_mode + 40);
        //try { 
           //_group_selection_mode.EnableMenuItem(selection_mode + 40, 1);
        //} catch(e){};
        
        mi("Selection mode").AppendMenuItem( MF_SEPARATOR, 0, 0); 

    MF_STRING = meta_artist ? EMI(data_main, 0) : MF_GRAYED;
    var artist_txt = mi_dim("Artist : ", meta_artist);
    _menu.AppendMenuItem( MF_STRING, 50, artist_txt + (data_main == 1 ? " *" : "")); 
    _menu.CheckMenuRadioItem(50, 50 , data_main + 50);
    //try { 
    //    _menu.EnableMenuItem(data_main + 50, 1);
    //} catch(e){};

    MF_STRING = meta_artist ? EMI(data_main, 1, data_sub, 0) : MF_GRAYED;
    _menu.AppendMenuItem( MF_STRING, 60, data_sub_value[0][0] + (data_main == 0 && data_sub == 0 ? " *" : "")); 
    
    MF_STRING = meta_artist ? EMI(data_main, 1, data_sub, 1) : MF_GRAYED;
    _menu.AppendMenuItem( MF_STRING, 61, data_sub_value[1][0] + (data_main == 0 && data_sub == 1 ? " *" : "")); 
    
    MF_STRING = meta_artist && meta_album ?  EMI(data_main, 1, data_sub, 2) : MF_GRAYED;
    var meta_album_txt = mi_dim(data_sub_value[2][0], meta_album);
    _menu.AppendMenuItem( MF_STRING, 62, meta_album_txt + (data_main == 0 && data_sub == 2 ? " *" : ""));

    MF_STRING = meta_artist && meta_title ?  EMI(data_main, 1, data_sub, 3) : MF_GRAYED;
    var meta_title_txt = mi_dim(data_sub_value[3][0], meta_title);
    _menu.AppendMenuItem( MF_STRING, 63, meta_title_txt + (data_main == 0 && data_sub == 3 ? " *" : ""));

    MF_STRING = meta_artist && meta_title ?  EMI(data_main, 1, data_sub, 4) : MF_GRAYED;
    var meta_title_txt = mi_dim(data_sub_value[4][0], meta_title);
    _menu.AppendMenuItem( MF_STRING, 64, meta_title_txt + (data_main == 0 && data_sub == 4 ? " *" : ""));

    if (data_main == 1){
        _menu.CheckMenuRadioItem(60, 64 , data_sub + 60);
        //try { 
        //    _menu.EnableMenuItem(data_sub + 60, 1);
        //} catch(e){};            
    }
    
    _menu.AppendMenuItem(MF_SEPARATOR, 0, 0);

    /////////////////////////////////////////////////////////////////////////////////////////   

    var _group_covers = window.CreatePopupMenu(); 
        MF_STRING = directory_path.indexOf("://") > 0 ? MF_GRAYED : MF_ENABLED;
        _group_covers.AppendTo(mi("Image source"), MF_STRING, "Image source : " + (covers_on ? "Covers" : "Last.fm"));

        _group_covers.AppendMenuItem( MF_ENABLED, 100, "Covers");
        _group_covers.CheckMenuItem(100, covers_on);
            
        _group_covers.AppendMenuItem( MF_SEPARATOR, 0, 0);
            
        _group_covers.AppendMenuItem( MF_ENABLED, 110, "External covers");
        _group_covers.CheckMenuItem(110, set_external);
        _group_covers.AppendMenuItem( MF_ENABLED, 120, "Embedded covers");
        _group_covers.CheckMenuItem(120, set_embedded);

        _group_covers.AppendMenuItem( MF_SEPARATOR, 0, 0);
            
        _group_covers.AppendMenuItem( EMI(set_priority, 0), 130, "Priority external");	
        _group_covers.AppendMenuItem( EMI(set_priority, 1), 131, "Priority embedded");	
        _group_covers.CheckMenuRadioItem(130, 131 , set_priority + 130);
        //try { 	
        //    _group_covers.EnableMenuItem(set_priority + 480, 1);
        //} catch(e){};

        _group_covers.AppendMenuItem( MF_SEPARATOR, 0, 0);
        
        _group_covers.AppendMenuItem( MF_ENABLED, 140, "over information");
        _group_covers.CheckMenuItem(140, over_info_on);
        
    if (mi_prop("Image source")) _menu.AppendMenuItem( MF_SEPARATOR, 0, 0);
    if (!mi_prop("Image source")) _group_20.AppendMenuItem( MF_SEPARATOR, 0, 0);

    ///////////////////////////////////////////////////////////////////////////////////////// 

    switch(ch()) {                                                                                       
    case "artist":  
        lastFm_query_menu_text = meta_artist ? meta_artist : "";
        lastFm_query = encodeURIComponent(meta_artist);
        break;              
    case "popular_albums":                                                                                
        lastFm_query_menu_text = header_2 ? header_2 : "";
        lastFm_query = encodeURIComponent(meta_artist) + "/" + encodeURIComponent(header_2);
        break;              
    case "similar":  
        lastFm_query_menu_text = header_1 ? header_1 : "";
        lastFm_query = encodeURIComponent(header_1);
        break;
    case "album": 
        lastFm_query_menu_text = meta_album ? meta_album : "";
        lastFm_query = encodeURIComponent(meta_artist) + "/" + encodeURIComponent(meta_album);
        break;    
    case "title":
    case "lyrics":
        lastFm_query_menu_text = meta_title ? meta_title : "";
        lastFm_query = encodeURIComponent(meta_artist) + "/" + (meta_album ? encodeURIComponent(meta_album) + "/" : "_/") + encodeURIComponent(meta_title);
        break;
    }  

    MF_STRING = lastFm_query_menu_text ? MF_ENABLED : MF_GRAYED;
    mi("last.fm").AppendMenuItem( MF_STRING, 200, mi_dim("last.fm : ", lastFm_query_menu_text));

    var _group_external_links = window.CreatePopupMenu();
        MF_STRING = external_links.length ? MF_ENABLED : MF_GRAYED;
        
        _group_external_links.AppendTo(mi("External links"), MF_STRING, "External links ...");
    
        for (var i = 210; i < external_links.length + 210; i += 2) {
            var links_txt = mi_dim("", external_links[i - 210]);
            _group_external_links.AppendMenuItem( MF_ENABLED, i, links_txt); 
        }
    
    MF_STRING = !history_on ? MF_ENABLED : MF_GRAYED;
    mi("Refresh").AppendMenuItem( MF_STRING, 220, "Refresh");
    mi("History").AppendMenuItem( MF_STRING, 230, "History");

    if (history_on){
        MF_STRING = history.length && selected_item ? MF_ENABLED : MF_GRAYED;
        _menu.AppendMenuItem( MF_STRING, 240, mi_dim("Delete ", selected_item ? selected_item : "..."));
        MF_STRING = history.length ? MF_ENABLED : MF_GRAYED;
        _menu.AppendMenuItem( MF_STRING, 250, "Clear history"); 
    }
    
    if (mi_prop("last.fm") || mi_prop("External links") || mi_prop("Refresh") || mi_prop("History") || history_on) _menu.AppendMenuItem( MF_SEPARATOR, 0, 0);
    if (!mi_prop("last.fm") || !mi_prop("External links") || !mi_prop("Refresh") || !mi_prop("History")) _group_20.AppendMenuItem( MF_SEPARATOR, 0, 0);
    
    var _group_remap = window.CreatePopupMenu(); 
        _group_remap.AppendTo(mi("Remap"), MF_ENABLED, "Remap");

        _group_remap.AppendMenuItem( MF_ENABLED, 260, "Remap " + title_case(remap_name()) + " name"); 
        _group_remap.AppendMenuItem( MF_ENABLED, 270, "View Remap list ");

    /////////////////////////////////////////////////////////////////////////////////////////    

    var _group_search_by = window.CreatePopupMenu(); 
        _group_search_by.AppendTo(mi("Search by"), MF_ENABLED, "Search by : " + search_by[search_by_idx]);
            
        _group_search_by.AppendMenuItem( EMI(search_by_idx, 0), 280, search_by[0]);
        _group_search_by.AppendMenuItem( EMI(search_by_idx, 1), 281, search_by[1]);
        _group_search_by.AppendMenuItem( EMI(search_by_idx, 2), 282, search_by[2]);
        _group_search_by.CheckMenuRadioItem(280, 282, search_by_idx + 280);
        //try { 
        //    _group_search_by.EnableMenuItem(search_by_idx + 150, 1);
        //} catch(e){}; 

    if (mi_prop("Remap") || mi_prop("Search by")) _menu.AppendMenuItem( MF_SEPARATOR, 0, 0);
    if (!mi_prop("Remap") || !mi_prop("Search by")) _group_20.AppendMenuItem( MF_SEPARATOR, 0, 0);

    var _group_text = window.CreatePopupMenu();
        _group_text.AppendTo(mi("Text"), MF_ENABLED, "Text");
        
        var _group_text_alignment = window.CreatePopupMenu();
            _group_text_alignment.AppendTo(_group_text, MF_ENABLED, "Text alignment");
        
            var _group_text_alignment_h1 = window.CreatePopupMenu();
                _group_text_alignment_h1.AppendTo(_group_text_alignment, MF_ENABLED, "Header 1 : " + text_alignment[text_alignment_h1][0]);
                
                _group_text_alignment_h1.AppendMenuItem( EMI(text_alignment_h1, 0), 300, text_alignment[0][0]);
                _group_text_alignment_h1.AppendMenuItem( EMI(text_alignment_h1, 1), 301, text_alignment[1][0]);
                _group_text_alignment_h1.AppendMenuItem( EMI(text_alignment_h1, 2), 302, text_alignment[2][0]);
                _group_text_alignment_h1.CheckMenuRadioItem( 300, 302, text_alignment_h1 + 300); 
                //try { 
                //    _group_text_alignment_h1.EnableMenuItem(text_alignment_h1 + 160, 1);
                //} catch(e){}; 

            var _group_text_alignment_h2 = window.CreatePopupMenu();
                _group_text_alignment_h2.AppendTo(_group_text_alignment, MF_ENABLED, "Header 2 : " + text_alignment[text_alignment_h2][0]);
                
                _group_text_alignment_h2.AppendMenuItem( EMI(text_alignment_h2, 0), 310, text_alignment[0][0]);
                _group_text_alignment_h2.AppendMenuItem( EMI(text_alignment_h2, 1), 311, text_alignment[1][0]);
                _group_text_alignment_h2.AppendMenuItem( EMI(text_alignment_h2, 2), 312, text_alignment[2][0]);
                _group_text_alignment_h2.CheckMenuRadioItem( 310, 312, text_alignment_h2 + 310);
                //try { 
                //    _group_text_alignment_h2.EnableMenuItem(text_alignment_h2 + 170, 1);
                //} catch(e){};  

            var _group_text_alignment_t = window.CreatePopupMenu();
                _group_text_alignment_t.AppendTo(_group_text_alignment, MF_ENABLED, "Main text : " + text_alignment[text_alignment_t][0]);
                
                _group_text_alignment_t.AppendMenuItem( EMI(text_alignment_t, 0), 320, text_alignment[0][0]);
                _group_text_alignment_t.AppendMenuItem( EMI(text_alignment_t, 1), 321, text_alignment[1][0]);
                _group_text_alignment_t.AppendMenuItem( EMI(text_alignment_t, 2), 322, text_alignment[2][0]);
                _group_text_alignment_t.CheckMenuRadioItem( 320, 322, text_alignment_t + 320); 
                
                //try { 
                //    _group_text_alignment_t.EnableMenuItem(text_alignment_t + 180, 1);
                //} catch(e){}; 

            var _group_text_alignment_t = window.CreatePopupMenu();
                _group_text_alignment_t.AppendTo(_group_text_alignment, MF_ENABLED, "Cover info : " + text_alignment[text_alignment_ci][0]);
                
                _group_text_alignment_t.AppendMenuItem( EMI(text_alignment_ci, 0), 330, text_alignment[0][0]);
                _group_text_alignment_t.AppendMenuItem( EMI(text_alignment_ci, 1), 331, text_alignment[1][0]);
                _group_text_alignment_t.AppendMenuItem( EMI(text_alignment_ci, 2), 332, text_alignment[2][0]);
                _group_text_alignment_t.CheckMenuRadioItem( 330, 332, text_alignment_ci + 330); 
                
                //try { 
                //    _group_text_alignment_t.EnableMenuItem(text_alignment_t + 180, 1);
                //} catch(e){}; 

        var _group_font_style = window.CreatePopupMenu();
            _group_font_style.AppendTo(_group_text, MF_ENABLED, "Font style");
        
            var _group_font_style_h1 = window.CreatePopupMenu();
                _group_font_style_h1.AppendTo(_group_font_style, MF_ENABLED, "Header 1 : " + font_style[font_style_h1][0]);
                
                _group_font_style_h1.AppendMenuItem( EMI(font_style_h1, 0), 340, font_style[0][0]);
                _group_font_style_h1.AppendMenuItem( EMI(font_style_h1, 1), 341, font_style[1][0]);
                _group_font_style_h1.AppendMenuItem( EMI(font_style_h1, 2), 342, font_style[2][0]);
                _group_font_style_h1.AppendMenuItem( EMI(font_style_h1, 3), 343, font_style[3][0]);
                _group_font_style_h1.CheckMenuRadioItem( 340, 343, font_style_h1 + 340); 
                //try { 
                //    _group_font_style_h1.EnableMenuItem(font_style_h1 + 190, 1);
                //} catch(e){}; 

            var _group_font_style_h2 = window.CreatePopupMenu();
                _group_font_style_h2.AppendTo(_group_font_style, MF_ENABLED, "Header 2 : " + font_style[font_style_h2][0]);
                
                _group_font_style_h2.AppendMenuItem( EMI(font_style_h2, 0), 350, font_style[0][0]);
                _group_font_style_h2.AppendMenuItem( EMI(font_style_h2, 1), 351, font_style[1][0]);
                _group_font_style_h2.AppendMenuItem( EMI(font_style_h2, 2), 352, font_style[2][0]);
                _group_font_style_h2.AppendMenuItem( EMI(font_style_h2, 3), 353, font_style[3][0]);
                _group_font_style_h2.CheckMenuRadioItem( 350, 353, font_style_h2 + 350); 
                //try { 
                //    _group_font_style_h2.EnableMenuItem(font_style_h2 + 200, 1);
                //} catch(e){}; 

            var _group_font_style_t = window.CreatePopupMenu();
                _group_font_style_t.AppendTo(_group_font_style, MF_ENABLED, "Main text : " + font_style[font_style_t][0]);
                
                _group_font_style_t.AppendMenuItem( EMI(font_style_t, 0), 360, font_style[0][0]);
                _group_font_style_t.AppendMenuItem( EMI(font_style_t, 1), 360, font_style[1][0]);
                _group_font_style_t.AppendMenuItem( EMI(font_style_t, 2), 362, font_style[2][0]);
                _group_font_style_t.AppendMenuItem( EMI(font_style_t, 3), 363, font_style[3][0]);
                _group_font_style_t.CheckMenuRadioItem( 360, 363, font_style_t + 360); 
                //try { 
                //    _group_font_style_t.EnableMenuItem(font_style_t + 210, 1);
                //} catch(e){}; 

            var _group_font_style_t = window.CreatePopupMenu();
                _group_font_style_t.AppendTo(_group_font_style, MF_ENABLED, "Cover info : " + font_style[font_style_ci][0]);
                
                _group_font_style_t.AppendMenuItem( EMI(font_style_ci, 0), 370, font_style[0][0]);
                _group_font_style_t.AppendMenuItem( EMI(font_style_ci, 1), 371, font_style[1][0]);
                _group_font_style_t.AppendMenuItem( EMI(font_style_ci, 2), 372, font_style[2][0]);
                _group_font_style_t.AppendMenuItem( EMI(font_style_ci, 3), 370, font_style[3][0]);
                _group_font_style_t.CheckMenuRadioItem( 370, 373, font_style_ci + 370); 
                //try { 
                //    _group_font_style_t.EnableMenuItem(font_style_t + 210, 1);
                //} catch(e){}; 


        _group_text.AppendMenuItem( MF_ENABLED, 380, "Text shadow");
        _group_text.CheckMenuItem( 380, text_shadow);
        
        _group_text.AppendMenuItem( MF_ENABLED, 390, "Show scrollbar");
        _group_text.CheckMenuItem( 390, scrollbar);
        
        _group_text.AppendMenuItem( MF_ENABLED, 400, "Tooltip");
        _group_text.CheckMenuItem( 400, tooltip);  
        
    /////////////////////////////////////////////////////////////////////////////////////////    

    var _group_image = window.CreatePopupMenu();
        _group_image.AppendTo(mi("Image"), MF_ENABLED, "Image");
        
        _group_image.AppendMenuItem( MF_ENABLED, 500, "Show Image");
        _group_image.CheckMenuItem( 500, img_show);
        
        _group_image.AppendMenuItem( MF_ENABLED, 510, "Place an image below the text");
        _group_image.CheckMenuItem( 510, img_below_text);
        
        _group_image.AppendMenuItem( MF_SEPARATOR, 0, 0); 
        
        var _group_image_alignment = window.CreatePopupMenu();
            _group_image_alignment.AppendTo(_group_image, MF_ENABLED, "Image alignment"); 

            _group_image_alignment.AppendMenuItem( EMI(img_alignment_idx, 0), 520, img_alignment[0]);
            _group_image_alignment.AppendMenuItem( EMI(img_alignment_idx, 1), 521, img_alignment[1]);
            _group_image_alignment.AppendMenuItem( EMI(img_alignment_idx, 2), 522, img_alignment[2]);
            _group_image_alignment.AppendMenuItem( EMI(img_alignment_idx, 3), 523, img_alignment[3]);
            _group_image_alignment.AppendMenuItem( EMI(img_alignment_idx, 4), 524, img_alignment[4]);
            _group_image_alignment.AppendMenuItem( EMI(img_alignment_idx, 5), 525, img_alignment[5]);
            _group_image_alignment.CheckMenuRadioItem( 520, 525, img_alignment_idx + 520);
            //try { 
            //    _group_image_alignment.EnableMenuItem(img_alignment_idx + 520, 1);
            //} catch(e){};

        var _group_download_quality = window.CreatePopupMenu();
            _group_download_quality.AppendTo(_group_image, MF_ENABLED, "Download quality : " + quality[quality_idx][0]);
            
            _group_download_quality.AppendMenuItem( EMI(quality_idx, 0), 530, quality[0][0]);
            _group_download_quality.AppendMenuItem( EMI(quality_idx, 1), 531, quality[1][0]);
            _group_download_quality.AppendMenuItem( EMI(quality_idx, 2), 532, quality[2][0]);
            _group_download_quality.CheckMenuRadioItem( 530, 532, quality_idx + 530);
            //try { 
            //    _group_download_quality.EnableMenuItem(quality_idx + 530, 1);
            //} catch(e){};

        if (covers_on) MF_STRING = covers[img_selected] && typeof covers[img_selected] != 'object' ? MF_ENABLED : MF_GRAYED;
        if (!covers_on) MF_STRING = img_file_names[img_selected] ? MF_ENABLED : MF_GRAYED; 
        
        _group_image.AppendMenuItem( MF_STRING, 540, "Open image");
        
        var _group_default_img = window.CreatePopupMenu();
        
            default_img_text = "";

            switch(true) {                                                                                       
            case def_img_on && !def_img_cover_on:  
                default_img_text = "selected image";
                break;              
            case def_img_cover_on:                                                                                
                default_img_text = "cover";
                break;              
            case !def_img_on && !def_img_cover_on:  
                default_img_text = "last Fm logo";
                break;   
            } 
        
            _group_default_img.AppendTo(_group_image, MF_ENABLED, "Default image : " + default_img_text); 
            
            _group_default_img.AppendMenuItem( MF_ENABLED, 550, "Default image");
            _group_default_img.CheckMenuItem( 550, def_img_on);
            
            _group_default_img.AppendMenuItem( MF_ENABLED, 560, "Covers as default image"); // 295  ???????????????????????
            _group_default_img.CheckMenuItem( 560, def_img_cover_on);
        
            var _group_lastFm_logo = window.CreatePopupMenu();
                MF_STRING = !def_img_on ? MF_ENABLED : MF_GRAYED;
                _group_lastFm_logo.AppendTo(_group_default_img, MF_STRING, "last.fm logo images");

                _group_lastFm_logo.AppendMenuItem( EMI(logo_img_idx, 0), 570, "1");   
                _group_lastFm_logo.AppendMenuItem( EMI(logo_img_idx, 1), 571, "2");   
                _group_lastFm_logo.AppendMenuItem( EMI(logo_img_idx, 2), 572, "3");  
                _group_lastFm_logo.AppendMenuItem( EMI(logo_img_idx, 3), 573, "4");    
                _group_lastFm_logo.AppendMenuItem( EMI(logo_img_idx, 4), 574, "5");  
                _group_lastFm_logo.CheckMenuRadioItem( 570, 574 , logo_img_idx + 570);
                //try { 
                //    _group_lastFm_logo.EnableMenuItem(logo_img_idx + 570, 1);
                //} catch(e){};
                
            _group_default_img.AppendMenuItem( MF_SEPARATOR, 0, 0);
            _group_default_img.AppendMenuItem( MF_ENABLED, 580, "Message : no default image ");
            _group_default_img.CheckMenuItem( 580, no_def_img_msg_on);

        _group_image.AppendMenuItem( MF_ENABLED, 590, "Border");
        _group_image.CheckMenuItem(590, img_border);

        _group_image.AppendMenuItem( MF_ENABLED, 600, "Fade effect");
        _group_image.CheckMenuItem(600, fade_effect);
        
        _group_image.AppendMenuItem( MF_ENABLED, 610, "Image download limit (" + limit + ")");
        
    if (mi_prop("Text") || mi_prop("Image")) _menu.AppendMenuItem( MF_SEPARATOR, 0, 0);
    if (!mi_prop("Text") || !mi_prop("Image")) _group_20.AppendMenuItem( MF_SEPARATOR, 0, 0);
    
    /////////////////////////////////////////////////////////////////////////////////////////    

    var _group_copy_to = window.CreatePopupMenu();
        MF_STRING = images.length ? MF_ENABLED : MF_GRAYED;
        _group_copy_to.AppendTo(mi("Copy to folder containing track"), MF_STRING, "Copy to folder containing track ...");
    
        _group_copy_to.AppendMenuItem( MF_STRING, 800, "Copy file");
        _group_copy_to.AppendMenuItem( MF_STRING, 810, "Copy files");

        mi("Copy to folder containing track").AppendMenuItem( MF_SEPARATOR, 0, 0); 

    var _group_storage = window.CreatePopupMenu();
        _group_storage.AppendTo(mi("Storage"), MF_ENABLED, "Storage");
        
        _group_storage.AppendMenuItem( MF_ENABLED, 820, "Save images and text");
        _group_storage.CheckMenuItem(820, save_images);

        _group_storage.AppendMenuItem( MF_ENABLED, 830, save_images ? "Use artist folder to save" : "Use artist folder for temporary storage");  
        _group_storage.CheckMenuItem(830, save_images_to_artist_folder); 
        
        _group_storage.AppendMenuItem( MF_SEPARATOR, 0, 0); 
        _group_storage.AppendMenuItem( MF_ENABLED, 840, "Delete temporary internet files");
        
        mi("Storage").AppendMenuItem( MF_SEPARATOR, 0, 0); 
 
    var _group_language_selection = window.CreatePopupMenu();
        _group_language_selection.AppendTo(mi("Language selection"), MF_ENABLED, "Language selection");
    
        for (var i = 20; i < language_text.length + 20; i++) {
            menuItem = language_text[i - 20][1];
            _group_language_selection.AppendMenuItem( MF_ENABLED, i, menuItem);   
            _group_language_selection.CheckMenuItem(i, window.GetProperty(language_text[i - 20][0]));
        }
        mi("Language selection").AppendMenuItem( MF_SEPARATOR, 0, 0); 

    mi("Help").AppendMenuItem( MF_ENABLED, 650, "Help ...");
    mi("Help").AppendMenuItem( MF_SEPARATOR, 0, 0);

    mi("Properties").AppendMenuItem( MF_ENABLED, 900, "Properties");
    mi("Configure").AppendMenuItem( MF_ENABLED, 910, "Configure ...");
    
    if (mi_prop("Properties") || mi_prop("Configure")) _menu.AppendMenuItem( MF_SEPARATOR, 0, 0);
    if (!mi_prop("Properties") || !mi_prop("Configure")) _group_20.AppendMenuItem( MF_SEPARATOR, 0, 0);
    
    _group_20.AppendMenuItem( MF_ENABLED, 920, "Main menu setting");
    
    _group_20.AppendTo(_menu, MF_ENABLED, "More ...");

    /////////////////////////////////////////////////////////////////////////////////////////    
    
    ret = _menu.TrackPopupMenu(x + 20, y - 100);
    if (ret == 0) return;
    
    switch (true) {
        case (ret >= 1 && ret < lang_arr.length + 1):
        lang_idx = ret - 1;
        window.SetProperty("lang", lang_idx);
        path = artist_folder_path(clean(meta_artist));
        get_text(path, meta_artist, meta_album, meta_title);
        break;
    }
    
    switch (true) {
        case (ret >= 20 && ret < language_text.length + 20):
        tmp_lang_idx = lang_arr[lang_idx];
        var tmp = window.GetProperty(language_text[ret - 20][0]);
        window.SetProperty(language_text[ret - 20][0], !tmp);
        create_lang_arr();
        path = artist_folder_path(clean(meta_artist));
        get_text(path, meta_artist, meta_album, meta_title);
        on_mouse_rbtn_up (x, y);
        break;
    }
    
    switch (true) {
        case (ret >= 210 && ret < external_links.length + 210):
        external_links_query = external_links[ret - 210 + 1];
        try {    
            WshShell.run(external_links_query);
        } catch (e) {};          
        break;
    }

    switch (ret) {
    // case 1 - 30: used
    case 40:
    case 41:
        album_old = ""; //////????????????????????
        title_old = ""; //////????????????????????
        selection_mode = ret - 40;
        window.SetProperty("selection mode", selection_mode);
        on_item_focus_change();
        break;
    case 50:
        data_main = 0;
        window.SetProperty("data_main", data_main); 
        if (history_on && lock_loading){
            history_on = false;
            lock_loading = false;
        }
        get_img(meta_artist, meta_album, meta_title);
        break;
    case 60:
    case 61:
    case 62:
    case 63:
    case 64:
        data_main = 1;
        window.SetProperty("data_main", data_main); 
        data_sub = ret - 60;
        window.SetProperty("data_sub", data_sub);
        if (history_on && lock_loading){
            history_on = false;
            lock_loading = false;
        }
        get_img(meta_artist, meta_album, meta_title);
        break;
        ////////////    covers
    case 100:
        covers_on = !covers_on;
        covers_on_old = covers_on;
        window.SetProperty("covers on", covers_on);
        covers_on && get_covers();
        !covers_on && get_img(meta_artist, meta_album, meta_title);
        img_size_recount = true;
        def_img_size_recount = true;
        break;
  case 110:
        set_external = set_external == false ? true : set_embedded == false ? true : false;
        window.SetProperty("external", set_external);
        img_selected = 0;
        get_external_covers(directory_path, tf_artist, tf_album);
        get_covers();
    break;
  case 120:
        set_embedded = set_embedded == false ? true : set_external == false ? true : false;
        window.SetProperty("embedded", set_embedded);
        img_selected = 0;
        get_embedded_covers(complete_path);
        get_covers();
    break;
  case 130:
  case 131:
        set_priority = set_priority == 0 ? 1 : 0;
        window.SetProperty("set priority", set_priority);
        img_selected = 0;
        get_covers();
    break;
    case 140:
        over_info_on = !over_info_on;
        window.setProperty("over info", over_info_on);
        img_size_recount = true;
        def_img_size_recount = true;
    break;
        ////////////    
    case 200:
        try {    
            WshShell.run("https://www.last.fm/" + lang_query(lang_idx) + "music/" + lastFm_query);
        } catch (e) {};
        break;
    // case 210: used
    case 220:                    //  Refresh
        refresh_data = true;
        on_metadb_changed();
        break;
    case 230:                   //  History
        history_query = true;
        history_on = true;
        lock_loading = true; 
        lock_mode();
        history_seach = "";
        clear_txt_var();
        get_history();
        break;
    case 240:
        del_history_item();
        break;
    case 250:
        del_history_list();
        break;  
    case 260:                   //  Remap
        edit_remap_list(meta_artist, tf_album, remap_name());
        break;
    case 270:                   //  Remap list
        if ( fso.FileExists(remap_file_path(remap_name())) ){
            try {
                objShellApp.ShellExecute("notepad.exe", remap_file_path(remap_name()),'' ,'open' , 1);
            } catch(e) {};
        }
        break; 
    case 280:
    case 281:
    case 282:
        search_by_idx = ret - 280;
        window.SetProperty("search by idx", search_by_idx);
        refresh_data = true;
        on_metadb_changed();
        break;
        ////////////    text
    case 300:
    case 301:
    case 302:
        text_alignment_h1 = ret - 300;
        window.SetProperty("text alignment : header 1", text_alignment_h1);
        window.Repaint();
        on_mouse_rbtn_up (x, y);
        break;  
    case 310:
    case 311:
    case 312:
        text_alignment_h2 = ret - 310;
        window.SetProperty("text alignment : header 2", text_alignment_h2);
        window.Repaint();	
        on_mouse_rbtn_up (x, y);
        break;  
    case 320:
    case 321:
    case 322:
        text_alignment_t = ret - 320;
        window.SetProperty("text alignment : text", text_alignment_t);
        window.Repaint();
        on_mouse_rbtn_up (x, y);
        break; 
    case 330:
    case 331:
    case 332:
        text_alignment_ci = ret - 330;
        window.SetProperty("text alignment : text ci", text_alignment_ci);
        window.Repaint();
        on_mouse_rbtn_up (x, y);
        break;
    case 340:
    case 341:
    case 342:
    case 343:
        font_style_h1 = ret - 340;
        window.SetProperty("text: font style: header 1", font_style_h1);
        get_font();
        get_text_arr(true);
        on_mouse_rbtn_up (x, y);
        break; 
    case 350:
    case 351:
    case 352:
    case 353:
        font_style_h2 = ret - 350;
        window.SetProperty("text: font style: header 2", font_style_h2);
        get_font();
        get_text_arr(true);
        on_mouse_rbtn_up (x, y);
        break; 
    case 360:
    case 361:
    case 362:
    case 363:
        font_style_t = ret - 360;
        window.SetProperty("text: font style: text", font_style_t);
        get_font();
        get_text_arr(true);
        on_mouse_rbtn_up (x, y);
        break; 
    case 370:
    case 371:
    case 372:
    case 373:
        font_style_ci = ret - 370;
        window.SetProperty("text: font style: text ci", font_style_ci);
        get_font();
        get_text_arr(true);
        on_mouse_rbtn_up (x, y);
        break; 
    case 380:
        text_shadow = !text_shadow;
        window.SetProperty("text: shadow", text_shadow);
        window.Repaint();
        break; 
    case 390:
        scrollbar = !scrollbar;
        window.SetProperty("scrollbar", scrollbar);
        get_text_arr(true);
        break; 
    case 400:
        tooltip = !tooltip;
        window.SetProperty("tooltip", tooltip);
        break; 
        ////////////    image
    case 500:
        img_show = !img_show;
        window.SetProperty("img show", img_show);
        def_fader_ini();
        break;
    case 510:    
        img_below_text = !img_below_text;
        window.SetProperty("img below text", img_below_text);
        img_size_recount = true;
        def_img_size_recount = true;
        break;
    case 520:
    case 521:
    case 522: 
    case 523:
    case 524:
    case 525:
        img_alignment_idx = ret - 520;
        window.SetProperty("align mode", img_alignment_idx);
        img_size_recount = true;
        def_img_size_recount = true;
        window.Repaint();
        break;
    case 530:
    case 531:
    case 532:    
        quality_idx = ret - 530;
        window.SetProperty("download quality", quality_idx);
        refresh_data = true;
        on_metadb_changed();
        break;
    case 540:
        if (covers_on){
            try {
                if (typeof covers[img_selected] != 'object') {
                    if (covers[img_selected]) WshShell.run( '"' + covers[img_selected] + '"' );	
                }				
            } catch(e) {};
        }
    
        if (!covers_on){   
            try {
                if (img_file_names[img_selected]) WshShell.run( '"' + img_file_names[img_selected] + '"' );	
            } catch(e) {};
        }
        break; 
    case 550:       //  Default image
        def_img_on = !def_img_on;
        window.SetProperty("default img", def_img_on);
        if (def_img_on) {
            def_img_cover_on = false;
            window.SetProperty("covers as default img", def_img_cover_on);
        }
        def_img_set();
        break;  
    case 560:       //  Covers as default image                     
        def_img_cover_on = !def_img_cover_on;
        window.SetProperty("covers as default img", def_img_cover_on);
        if (def_img_cover_on) {
            def_img_on = false;
            window.SetProperty("default img", def_img_on);
        }
        def_img_set();
        break;
    case 570:
    case 571:
    case 572: 
    case 573:
    case 574:
        logo_img_idx = ret - 570;
        window.SetProperty("logo_img_idx", logo_img_idx);
        def_img_set();
        break;
    case 580:
        no_def_img_msg_on = !no_def_img_msg_on;
        window.SetProperty("no def img msg on", no_def_img_msg_on);
        break;
    case 590:
        img_border = !img_border;
        window.SetProperty("img border", img_border);
        img_size_recount = true;
        def_img_size_recount = true;
        window.Repaint();
        break;
    case 600:
        fade_effect = !fade_effect;
        window.SetProperty("fade effect", fade_effect);
        def_fader_ini();
        break; 
    case 610:
        download_limit(x, y);
        break;
        ////////////    
    case 800:
        copy_files(0);
        break;
    case 810:
        copy_files(1);
        break;
    case 820:
        save_images = !save_images;
        window.SetProperty("save images", save_images);
        break;
    case 830:
        save_images_to_artist_folder = !save_images_to_artist_folder;
        window.SetProperty("save to artist folder containing track", save_images_to_artist_folder);
        break       
    case 840:
        try {
            WshShell.Run("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8");
            //WshShell.Run("RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2");
        } catch (e) {};
        break; 
    case 850:
        help();
        break;
    case 900:
        window.ShowProperties();
        break;   
    case 910:
        window.ShowConfigure();   
        break;
    case 920:
        main_menu_setting(x, y);
        break;
    }
    _menu.Dispose(); 
    _group_20.Dispose(); 
    _group_selection_mode.Dispose();
    _group_external_links.Dispose();
    _group_remap.Dispose();
    _group_search_by.Dispose(); 	
    _group_text.Dispose();
    _group_text_alignment.Dispose();
    _group_text_alignment_h1.Dispose();
    _group_text_alignment_h2.Dispose();
    _group_text_alignment_t.Dispose();
    _group_font_style.Dispose();
    _group_font_style_h1.Dispose();
    _group_font_style_h2.Dispose();
    _group_font_style_t.Dispose();
    _group_image.Dispose();
    _group_image_alignment.Dispose();
    _group_download_quality.Dispose();
    _group_default_img.Dispose();
    _group_lastFm_logo.Dispose();
    _group_covers.Dispose();    
    _group_copy_to.Dispose();
    _group_storage.Dispose(); 
    _group_language_selection.Dispose();
    return true;
} 

function download_limit(x, y){
    var _menu = window.CreatePopupMenu();

    _menu.AppendMenuItem(MF_ENABLED, 1, "Increase"); 
    _menu.AppendMenuItem(MF_ENABLED, 2, "Download limit " + limit); 
    _menu.AppendMenuItem(MF_ENABLED, 3, "Decrease"); 

    ret = _menu.TrackPopupMenu(x, y);

    switch (ret) {
    case 1:
        limit = limit + 1;
        window.SetProperty("img download limit", limit);
        download_limit(x, y);
        break;
    case 2:
        on_mouse_rbtn_up (x, y);
        break;
    case 3:
        limit = limit <= 1 ? 1 : limit - 1;
        window.SetProperty("img download limit", limit);
        download_limit(x, y);
        break;
    }
    _menu.Dispose();
}

function get_files_if_loaded(img_refresh, path, artist, album, title){
    if (!meta_artist) return; 
    switch(ch()) {                                                                                       
    case "artist":
    case "popular_albums":
    case "similar":  
        if (artist && artist != meta_artist) return; 
        break;
    case "album":
        if (artist && artist != meta_artist || album && album != meta_album) return; 
        break;    
    case "title":
    case "lyrics":
        if (artist && artist != meta_artist || title && title != meta_title) return;
        break;
    }  

    if (img_refresh && !covers_on){
        var i = 0;
        get_files_timer && window.ClearInterval(get_files_timer); 
        get_files_timer = window.SetInterval(function() {	
            i++;
            get_img_from_dir(path, clean(artist), clean(album), clean(title));
            if (images.length > 0 || i >= 20) {
                if (i < 20){
                    next_image_lastFm(0);
                }
                img_refresh = false;
                window.ClearInterval(get_files_timer);
            }
        }, 500);
    }   
    get_text(path, artist, album, title);
}

function cycle_set_timer(){
cycle_timer && window.ClearInterval(cycle_timer);
cycle_timer = window.SetInterval(function() {
        cycle_step =  cycle_set ? 0 : cycle_step + 1;
        if (cycle > 0 && cycle_step >= cycle){
            if (!covers_on && images.length > 1){
                if (images.length < limit) get_img_from_dir(artist_folder_path(clean(meta_artist)), meta_artist); 
                
                next_image_lastFm(1);
                
                if (ch() == "popular_albums" || ch() == "similar"){
                    path = artist_folder_path(clean(meta_artist));
                    get_text(path, meta_artist, meta_album, meta_title);
                }
            }

            if (covers_on && covers.length > 1){
                next_image_covers(1);
            }
            cycle_step = 0;
        }
}, 1000);			
}			
			
function delay_1(){
    delay = true;	
    var delay_timer = window.SetTimeout(function() {			
        delay = false;		
        window.ClearTimeout(delay_timer);			
    }, 200);
}

function def_img_set(){
    if (g_img) {
        g_img = null;
        window.Repaint();
    }
    def_fader_ini();
    def_img_ini();
    logo_img_ini();
    var delay_timer = window.SetTimeout(function() {			
        if (!covers_on) images[img_selected] && next_image_lastFm(0);
        if (covers_on) covers[img_selected] && next_image_covers(0);
        window.ClearTimeout(delay_timer);	
        window.Repaint();		
    }, 1500);
}

function fader_timer(){
    img_size = calc_img_size(g_img);
ftimer && window.ClearInterval(ftimer);
ftimer = window.SetInterval(function() {
        fader = fader == 0 ? 1 : fader * 2;
        window.RepaintRect(img_size.x - img_border_width, img_size.y - img_border_width, img_size.w + img_border_width * 2, img_size.h + img_border_width * 2);      
        if (fader >= 255) {
            fader = 255;
            window.ClearInterval(ftimer);
        }
}, 50);
}

function fader_timer_logo(){
ftimer_logo && window.ClearInterval(ftimer_logo);
ftimer_logo = window.SetInterval(function() {
        logo_fader = logo_fader == 0 ? 1 : logo_fader * 2;
        window.Repaint();
        if (logo_fader >= logo_img_transp) {
            logo_fader = logo_img_transp;
            window.ClearInterval(ftimer_logo);
        }
}, 50);
}

function fader_timer_def_img(){
    def_img_size = calc_img_size(def_img);
ftimer_def_img && window.ClearInterval(ftimer_def_img);
ftimer_def_img = window.SetInterval(function() {
        def_img_fader = def_img_fader == 0 ? 1 : def_img_fader * 2;
        window.RepaintRect(def_img_size.x - img_border_width, def_img_size.y - img_border_width, def_img_size.w + img_border_width * 2, def_img_size.h + img_border_width * 2);  
        if (def_img_fader >= def_img_transp) {
            def_img_fader = def_img_transp;
            window.ClearInterval(ftimer_def_img);
        }
}, 50);
}

function info_tooltip() {
    tooltip_on = true;
    tooltip_timer &&  window.ClearTimeout(tooltip_timer);
    tooltip_timer = window.SetTimeout(function() {
        tooltip_on = false;
        tooltip_text = "";
        window.Repaint();
        tooltip_timer && window.ClearTimeout(tooltip_timer);
    },  tooltip_delay);
}

function load_lastFm_logo(){
    urls = [
    "https://www.last.fm/static/images/footer_logo@2x.49ca51948b0a.png",
    "https://d2r1vs3d9006ap.cloudfront.net/public/uploaded_images/10596530/logo_sq_256_new_small.png", // no
    "https://www.last.fm/static/images/logo_static.png?7b581436b23f",
    "http://cdn.shopify.com/s/files/1/0270/7261/t/3/assets/logo.png?13435600546523064478", // "https://cdn.last.fm/images/logo.svg"
    "http://cdn.shopify.com/s/files/1/0270/7261/t/1/assets/logo.png?13435600546523064478"
    ];
    
    for (var i = 0; i < urls.length; i++) {
        file = "logo_" + (i + 1) + ".png";
        if(!fso.FileExists(script_path + file)) { 
            var path = "\"" + script_path + file + "\"";
            WshShell.Run(vbs + " " + urls[i] + " " + path, false);
        }            
    }
    
    url = "https://www.last.fm/static/images/marvin.05ccf89325af.png" // "http://cdn.last.fm/images/marvin_tea.svg
    file = "marvin.png";
    if(!fso.FileExists(script_path + file)) { 
        var path = "\"" + script_path + file + "\"";
        WshShell.Run(vbs + " " + url + " " + path, false);
    }  
}

function create_download_file() {
    try {
        file = fso.CreateTextFile(script_path + "download.vbs" );
       
        var text =   
            "If (WScript.Arguments.Count <> 2) Then" + "\n\r" +   
            "   WScript.Quit" + "\n\r" +
            "End If" + "\n\r" + "\n\r" +   

            "url = WScript.Arguments(0)" + "\n\r" +   
            "file = WScript.Arguments(1)" + "\n\r"  + "\n\r" +   

            "Set objFSO = Createobject(" + '"Scripting.FileSystemObject"' + ")" + "\n\r" +   
            "If objFSO.Fileexists(file) Then" + "\n\r" +   
            "   Set objFSO = Nothing" + "\n\r" +
            "   WScript.Quit" + "\n\r" +
            "End If" + "\n\r" + "\n\r" +   

            "Set objXMLHTTP = CreateObject(" + '"MSXML2.XMLHTTP"' + ")" + "\n\r" +   
            "objXMLHTTP.open " + '"GET"' + ", url,false" + "\n\r" +   
            "objXMLHTTP.send()" + "\n\r" + "\n\r" +   

            "If objXMLHTTP.Status = 200 Then" + "\n\r" +   
            "   Set objADOStream = CreateObject(" + '"ADODB.Stream"' + ")" + "\n\r" +
            "   objADOStream.Open" + "\n\r" +
            "   objADOStream.Type = 1" + "\n\r" +
            "   objADOStream.Write objXMLHTTP.ResponseBody" + "\n\r" +
            "   objADOStream.Position = 0" + "\n\r" +
            "   objADOStream.SaveToFile file" + "\n\r" +
            "   objADOStream.Close" + "\n\r" +
            "   Set objADOStream = Nothing" + "\n\r" +
            "End If" + "\n\r" + "\n\r" +   

            "Set objFSO = Nothing" + "\n\r" +   
            "Set objXMLHTTP = Nothing"   
        ;

        file.WriteLine(text);
        file.Close();
    } catch(e) {};
}

function on_mouse_move(x, y) {
    window.SetCursor(IDC_HAND);
    
    pos_x = x;
    pos_y = y; 
    
    on_header_0 = x >= txt_x && x < ww && y >= txt_y && y < h0_y + h0_text_row_height * h0_text_arr.length ? true : false;
    on_header_1 = x >= txt_x && x < ww && y >= h1_y && y < h1_y + h1_text_row_height * h1_text_arr.length ? true : false;
    on_years_active_btn = x >= txt_x && x < ww && y >= h1_y + h1_text_row_height * h1_text_arr.length && y < h2_y ? true : false;
    on_header_2 = x >= txt_x && x < ww && y >= h2_y && y < h2_y + h2_text_row_height * h2_text_arr.length ? true : false;
    on_info_text_btn = x >= txt_x && x < ww && y >= t_y - text_row_height && y < t_y ? true : false;
    on_text = x >= txt_x && x < seekbar_x && y >= t_y && y <= wh ? true : false;
    on_scrollbar = x >= seekbar_x && x < ww && y >= t_y && y <= wh ? true : false;
    on_seekbar = x >= seekbar_x && x < ww && y >= seekbar_y && y <= seekbar_y + seekbar_h ? true : false;
    on_img = !on_header_0 && !on_header_1 && !on_years_active_btn && !on_header_2 && !on_info_text_btn && !on_text && !on_scrollbar ? true : false;

    if (on_text_down){
        txt_x = x - delta_x;
        txt_y = y - delta_y;

        txt_x = Math.round(Math.max(0, Math.min(txt_x, ww - t_margin * 2 - h1_char_width - (scrollbar ? seekbar_w + 10 : 0))));
        txt_y = Math.round(Math.max(0, Math.min(txt_y, wh - (h1_text_row_height + t_margin * 2))));
        
        if (!cut) cut_text();

        get_text_arr(false);
        
        if (!img_below_text) {img_size_recount = true; def_img_size_recount = true;}
    }
    
    if (on_seekbar_down){
        seekbar_posy = y + delta_y;
        scroll = y + delta_y >= 0 ? y + delta_y <= (text_rows - text_rows_per_panel) * seekbar_k ? Math.round(seekbar_posy / seekbar_k) : text_rows - text_rows_per_panel : 0;
        scroll = scroll * - 1 * text_row_height; 
        scroll_check();	
    }

    if (scrollbar && seekbar_x && seekbar_y && seekbar_h && !on_text_down){
        window.RepaintRect(seekbar_x, t_y, ww, wh);	
    }

    if (!on_text_down){ // info_text_btn
        window.RepaintRect(txt_x, t_y - text_row_height, ww, text_row_height);
    }
    
    if (!on_text_down){ // on_years_active_btn
        window.RepaintRect(txt_x, h1_y + h1_text_row_height * h1_text_arr.length, ww, h1h2_y_delta);
    }
    
    if (lock_loading){  // lock_btn
        window.RepaintRect(t_x, txt_y, ww, h0_y + h0_text_row_height * h0_text_arr.length);
    }

    if (on_header_1 && on_text_down) {							
        text_hiden = false;							
        window.SetProperty("txt hiden", text_hiden);							
    }	

    tooltip && tooltip_on && window.Repaint();
    
    if (x_old != x || y_old != y){
        get_text_idx();
        get_selected_item();
        x_old = x;
        y_old = y;
    }
}
	
function on_mouse_wheel(delta) {	
    if (on_img && !cycle_set && !delay && !history_on){	
        if (!covers_on && images.length > 1){
            
            if (images.length < limit) {
                get_img_from_dir(artist_folder_path(clean(meta_artist)), meta_artist); 
            }

            delay_1();	
            next_image_lastFm(delta);
            
            if  (ch() == "popular_albums" || ch() == "similar"){
                path = artist_folder_path(clean(meta_artist));
                get_text(path, meta_artist, meta_album, meta_title);
            }
        }

        if (covers_on && covers.length > 1){
            delay_1();	
            next_image_covers(delta); 
        }

        if (cycle > 0) cycle_step = 0;	
    }							

    if ((on_header_0 || on_header_1 || on_years_active_btn || on_header_2 || on_info_text_btn || on_text || on_seekbar || on_scrollbar) && !ShiftDown && !ControltDown){	
        if (text_height > text_rows_per_panel_height){
            wheel_id += delta;
            scroll += wheel_id * text_row_height * (on_seekbar || on_scrollbar ? text_rows_per_panel : 1); 
            scroll_check();	
        }
    }
   							
    if ((on_header_0 || on_header_1 || on_header_2 || on_text) && ShiftDown && !delay && !ControltDown && !text_hiden){
        delay_1();	

        if (on_header_0 && lock_loading){
            font_size_h0 = tooltip_text = Math.max(font_size_min, Math.min(font_size_max, font_size_h0 += delta * 1));
            window.SetProperty("text: font size: header 0", font_size_h0);
        }        

        if (on_header_1 && !history_on){
            font_size_h1 = tooltip_text = Math.max(font_size_min, Math.min(font_size_max, font_size_h1 += delta * 1));
            window.SetProperty("text: font size: header 1", font_size_h1);
        }
        
        if (on_header_2 && ch() != "artist" && ch() != "similar"){
            font_size_h2 = tooltip_text = Math.max(font_size_min, Math.min(font_size_max, font_size_h2 += delta * 1));
            window.SetProperty("text: font size: header 2", font_size_h2);
        }
        
        if (on_text){
            font_size_t = tooltip_text = Math.max(font_size_min, Math.min(font_size_max, font_size_t += delta * 1));
            window.SetProperty("text: font size: text", font_size_t);
        }            

        get_font();							
        get_text_arr(true);	
    }							
							
    if ((on_header_0 || on_header_1 || on_header_2 || on_text) && !ShiftDown && ControltDown){	
        bg_transparence = tooltip_text = Math.max(0, Math.min(255, bg_transparence += delta * 10));
        window.SetProperty("text bg transparence (0-255)", bg_transparence);
        window.Repaint();							
    }							
							
    if (on_img && cycle_set && ShiftDown) {		
        cycle = Math.max(0, Math.min(60, cycle += delta * 5));
        window.SetProperty("auto cycle (sec)", cycle);							
        window.Repaint();							
    }
        
    tooltip && tooltip_text && info_tooltip();
}		
							
function on_mouse_lbtn_down(x, y){							
    if (on_header_0 || on_header_1 || on_years_active_btn || on_header_2 || on_info_text_btn || on_text){							
        on_text_down = true;							
        delta_x = x - txt_x;							
        delta_y = y - txt_y;
    }

    if (on_seekbar){
        on_seekbar_down = true;
        seekbar_posy = Math.abs(scroll) / text_row_height * seekbar_k;
        delta_y = seekbar_posy - y;
    }

    if (on_scrollbar && !on_seekbar){
        on_scrollbar_down = true;
        scroll = (y - t_y) / seekbar_k * text_row_height * -1; 
        scroll = Math.floor(scroll / text_row_height) * text_row_height;
        scroll_check();	
    }

    if (tooltip_on){
        tooltip_on = false;
        window.Repaint();
    }
}

function on_mouse_lbtn_up(x,y){
    window.SetProperty("txt_x", txt_x);
    window.SetProperty("txt_y", txt_y);
    on_text_down = false;
    on_seekbar_down = false;
    on_scrollbar_down = false;
    restore_cut_text();
}

function lock_mode(){
    if (!lock_loading){
        if (history_on){
            history_on = false;
            artist_old = album_old = title_old = "";
            history = [];
        }
        on_metadb_changed(); 
    }
    get_text_arr(true);
}

function on_mouse_lbtn_dblclk (x, y){
    if (on_header_0 || on_header_1){
        lock_loading = !lock_loading; 
        lock_mode();
    }

    if (on_text && lang_arr.length && !selected_item && !history_on && ch() != "lyrics"){
        if (ShiftDown) {
            lang_idx = lang_idx <= 0 ? lang_arr.length - 1 : lang_idx - 1;
        } else {
            lang_idx = lang_idx >= lang_arr.length - 1 ? 0 : lang_idx + 1;
        }
        
        window.SetProperty("lang", lang_idx);
        path = artist_folder_path(clean(meta_artist));
        get_text(path, meta_artist, meta_album, meta_title);
        tooltip_text = get_text_menu(lang_arr[lang_idx]);
        tooltip && tooltip_text && info_tooltip();
    }
    
    if (on_text && selected_item){
        if (selected_item == latest_release){
            data_main = 1;	
            data_sub = 2;
            meta_album = latest_release;
            get_img(meta_artist, meta_album, meta_title);	
        }
        
        if (selected_item == from_the_album){
            data_main = 1;	
            data_sub = 2;
            meta_album = from_the_album;
            get_img(meta_artist, meta_album, meta_title);	
        }
        
        if (selected_item == popular_this_week){
            data_main = 1;	
            data_sub = 3;
            meta_title = popular_this_week; 
            get_img(meta_artist, meta_album, meta_title);	
        } 
        
        if (history_on){
            history_on = false;
            data_main = 0;
            tf_artist = selected_item;
            tf_album = "";
            tf_title = "";
            on_metadb_changed();
        }
    }        

    if (on_img){
        if (!history_on){
            data_main = data_main == 1 ? 0 : 1;
            window.SetProperty("data_main", data_main);
            get_img(meta_artist, meta_album, meta_title);

            switch(data_main) {
            case 0:
                tooltip_text = "artist";
                break;
            case 1:
                tooltip_text = data_sub_value[data_sub][2].replace(/_/g," ");
                break;
            }
            meta_artist && tooltip && tooltip_text && info_tooltip();
        }
    }
    
    if (on_years_active_btn){
        if (ch() == "artist" || ch() == "similar"){
            years_active_on = !window.GetProperty("years active " + ch());
            window.SetProperty("years active " + ch(), years_active_on);
            scroll = scroll_ = scroll__ = scroll___ = 0;
            get_text_arr(true);
        }
    }
    
    if (on_info_text_btn){							
        info_text_on = !window.GetProperty("info text " + ch());
        window.SetProperty("info text " + ch(), info_text_on);
        scroll = scroll_ = scroll__ = scroll___ = 0;
        get_text_arr(true);
    }
}

function on_mouse_mbtn_dblclk (x, y){
    !text_hiden && hide_text(x, y);
    text_hiden && recover_hidden_text(); 
    text_hiden = !text_hiden;
    window.SetProperty("txt hiden", text_hiden);
        
    window.SetProperty("txt_x", txt_x);
    window.SetProperty("txt_y", txt_y);
}

function on_mouse_leave() {
    window.SetCursor(IDC_ARROW);
    on_header_0, on_header_1, on_years_active_btn, on_header_2, on_info_text_btn, on_text, on_scrollbar, on_seekbar, on_img = false;
    window.Repaint(); 
}

function on_char(code) {
    if (history_on){
        history_query = true;
        e_char = String.fromCharCode(code); 
        switch(code){    
        case ESC:
            history_seach = "";
            get_history();
            break;
        case BACKSPACE:
            history_seach = history_seach.substring(0, history_seach.length - 1);
            get_history();
            break;
        case CTRLV:
            clipboardData = htmlfile.parentWindow.clipboardData.getData('text');
            clipboardData = clipboardData.substring(0, 200);
            clipboardData = clipboardData.replace(/[\n\r]/g,' ');
            history_seach = trim(clipboardData);
            get_history();
            break;
        case ENTER:
            if (history_on && !history_result){ 
                get_lastFm_artist(trim(history_seach));
                history_seach = "Search ...";
                get_history();
            }
        
            if (history_on && selected_item && history_result){
                history_on = false;
                data_main = 0;
                tf_artist = selected_item;
                tf_album = "";
                tf_title = "";
                on_metadb_changed();
            }
            break;
        default: // any character
            history_seach =  (history_seach + e_char).replace(/\s{1,}/g," ");
            get_history();
            break;
        }
    }
}

function on_key_down(vkey) {
    switch(vkey){
    case VK_SHIFT:
        ShiftDown = true;
        cycle_set = true;

        if (!text_hiden){
            tooltip_text = "";
            if (on_header_0 && lock_loading) tooltip_text = font_size_h0;
            if (on_header_1 && !history_on) tooltip_text = font_size_h1;
            if (on_header_2 && ch() != "artist" && ch() != "similar") tooltip_text = font_size_h2;
            if (on_text) tooltip_text = font_size_t;
            tooltip && tooltip_text && info_tooltip();
        }

        window.Repaint();
        break;
    case VK_CONTROL:
        ControltDown = true;
        tooltip_text = "";
        if (on_header_0 || on_header_1 || on_header_2 || on_text) tooltip_text = bg_transparence;
        tooltip && tooltip_text && info_tooltip();
        
        window.Repaint();							
        break;
    case VK_DELETE:
        if (history_on) del_history_item();
        break;
    }

    if (!cycle_set && !delay && !history_on){
        if (!covers_on && images.length > 1){ 
            delay_1();
        
            switch(vkey){  
            case VK_LEFT:
                next_image_lastFm(-1);
                break;
            case VK_RIGHT:
                next_image_lastFm(1);
                break;  
            }
        
            if (vkey == VK_LEFT || vkey == VK_RIGHT){
                if (ch() == "popular_albums" || ch() == "similar"){
                    path = artist_folder_path(clean(meta_artist));
                    get_text(path, meta_artist, meta_album, meta_title);
                }
            }        
        }
    
        if (covers_on && covers.length > 1){
            delay_1();
        
            switch(vkey){  
            case VK_LEFT:
                next_image_covers(-1);
                break;
            case VK_RIGHT:
                next_image_covers(1);
             break;  
            }  
        }
        if (cycle > 0) cycle_step = 0;
    }

    if (text_height > text_rows_per_panel_height || history_on){
        key_down = true;
        switch(vkey){
        case VK_UP:
            if (!history_on){
                scroll = scroll + text_row_height;
                scroll_check();	
            }
            
            if (history_on && text_idx > 0){
                if (text_idx <= (Math.abs(scroll) / text_row_height) && text_rows > text_rows_per_panel){
                    scroll = scroll + text_row_height;
                    scroll_check();	
                } 
 
                text_idx = Math.max(text_idx - 1, 0);
                get_selected_item();
            }
            break;
        case VK_DOWN:
            if (!history_on){
                scroll = scroll - text_row_height;
                scroll_check();	
            }
            
            if (history_on && text_idx < text_rows){
                if (text_idx >= (Math.abs(scroll) / text_row_height) + text_rows_per_panel - 1 && text_rows > text_rows_per_panel){
                    scroll = scroll - text_row_height;
                    scroll_check();	
                } 

                text_idx = Math.min(text_idx + 1, text_rows - 1);
                get_selected_item();
            }
            break;
        case VK_HOME:
            scroll = 0;
            text_idx = 0;
            scroll_check();	
            break;
        case VK_END:
            scroll = -1 * (text_height - text_rows_per_panel_height);
            text_idx = text_rows - 1;
            scroll_check();	
            break;
        case VK_PAGE_UP: 
            if (text_rows > text_rows_per_panel){
                scroll += text_row_height * text_rows_per_panel;
                text_idx = Math.max(text_idx - text_rows_per_panel, 0);
                scroll_check();	
            }
            break;
        case VK_PAGE_DOWN:  
            if (text_rows > text_rows_per_panel){
                scroll -= text_row_height * text_rows_per_panel;
                text_idx = Math.min(text_idx + text_rows_per_panel, text_rows - 1);
                scroll_check();	
            }
            break;
        }
    }
}

function on_key_up(vkey) {
    switch(vkey){
    case VK_SHIFT:
        ShiftDown = false;
        cycle_set = false; 
        if (cycle > 0) cycle_set_timer();
        if (cycle == 0) window.ClearInterval(cycle_timer);
        window.Repaint(); 
        break;
    case VK_CONTROL:
        ControltDown = false;
        break;
    }
}

function hide_text(x, y){  
    window.SetProperty("tmp_txt_x", txt_x);
    window.SetProperty("tmp_txt_y", txt_y);

    txt_x = ww - t_margin * 2 - h1_char_width - (scrollbar ? seekbar_w + 10 : 0);
    txt_y = wh - (h1_text_row_height + t_margin * 2);
    if (!img_below_text) {img_size_recount = true; def_img_size_recount = true;}
    get_text_arr(true);
}

function recover_hidden_text(){  
    txt_x = window.GetProperty("tmp_txt_x");
    txt_y = window.GetProperty("tmp_txt_y");
    if (!img_below_text) {img_size_recount = true; def_img_size_recount = true;}
    get_text_arr(true);
}

function on_size(){
    ww = window.Width;   
    wh = window.Height;
   
    txt_x = window.GetProperty("txt_x");
    txt_y = window.GetProperty("txt_y");

    txt_x = Math.round(Math.max(0, Math.min(txt_x, ww - t_margin * 2 - h1_char_width - (scrollbar ? seekbar_w + 10 : 0))));
    txt_y = Math.round(Math.max(0, Math.min(txt_y, wh - (h1_text_row_height + t_margin * 2))));

    img_size_recount = true;
    def_img_size_recount = true;
    get_text_arr(true);
}

function del_folders(n){
    var dir = fso.GetFolder(work_path);
    var e = new Enumerator( dir.SubFolders );
    try {
        for(; !e.atEnd(); e.moveNext() ) {
            var sub_folder = e.item().Name;
            if (sub_folder.indexOf("_download") < 0){
                if (sub_folder.indexOf(n) < 0){
                    fso.deleteFolder(work_path + sub_folder, true);	
                }	
            }   	
        }	
    } catch(e) {};	
}

function del_folder(n){
    if(!n) return;
    try {
        fso.deleteFolder(n, true);	
    } catch(e) {};	
}

function del_empty_folders(){
    var dir = fso.GetFolder(work_path);

    var e = new Enumerator( dir.SubFolders );
    try {
        for(; !e.atEnd(); e.moveNext() ) {
            var sfolder = fso.GetFolder(e.item() + "\\");
            var i = new Enumerator( sfolder.Files );
            var data = 0;
            for(; !i.atEnd(); i.moveNext() ) {
                var name = i.item().Name;
                if (name.match(/\.(jpg|txt)$/i)) {
                    data++;
                }
            }

            if (e.item().Name.indexOf("_download") < 0 && data == 0){
                fso.deleteFolder(e.item(), true);
            }
        }
    } catch(e) {};
}
/*
function del_empty_folders(){
    var dir = fso.GetFolder(work_path);

    var e = new Enumerator( dir.SubFolders );
    try {
        for(; !e.atEnd(); e.moveNext() ) {
            var sub_folder = objShellApp.NameSpace( e.item() + "\\" );
            var items = sub_folder.Items();
            var items_count = items.Count;

            if (!items_count){
                fso.deleteFolder(e.item(), true);
            }
        }
    } catch(e) {}
}
*/   
function calc_img_size(img){
    if(!img) return;
    
    ww = window.Width;   								
    wh = window.Height;								

    var size = {x:0, y:0, w:0, h:0, cx:0, cy:0, cw:0, ch:0};
    
    var margin = img_margin ? img_margin : 0;
    var border = img_border && img_border_width > 0 ? img_border_width : 0;
    var new_width = ww - border * 2 - margin * 2;
    
    var ci_text_delta = covers_on && ci_text_arr.length && over_info_on ? ci_text_height + ci_text_row_height / 2 + t_margin : 0;
    
    if (img_below_text){
        var new_height = wh - ci_text_delta - border * 2 - margin * 2;
    } else {
        var new_height = txt_y - ci_text_delta - border * 2 - margin * 2;
    }

    switch(img_alignment_idx) {	
	case 0: // adjust
        var sw = new_width / img.Width;								
        var sh = new_height / img.Height;								
        var s = Math.min(sw, sh);								
        								
        var x = border + margin;								
        var y = border + margin;								
        								
        if (sw > sh) x = x + (new_width - img.Width * s) / 2;								
        else if (sw < sh) y = y + (new_height - img.Height * s) / 2;								

        var width = img.Width * s;								
        var height = img.Height * s;								
        var cx = 0;								
        var cy = 0;								
        var cwidth = img.Width;								
        var cheight = img.Height;								
		break;						
				
    case 1: // adjust top - center								
        var sw = new_width / img.Width;								
        var sh = new_height / img.Height;								
        var s = Math.min(sw, sh);								
								
        var x = border + margin;								
        if (sw > sh) x = x + (new_width - img.Width * s) / 2;	
        var y = border + margin;							
        var width = img.Width * s;								
        var height = img.Height * s;								
        var cx = 0;								
        var cy = 0;								
        var cwidth = img.Width;								
        var cheight = img.Height;								
		break;	
        		
    case 2: // adjust top - left		
        var sw = new_width / img.Width;		
        var sh = new_height / img.Height;		
        var s = Math.min(sw, sh);		
        		
        var x = border + margin;		
        var y = border + margin;		
        var width = img.Width * s;		
        var height = img.Height * s;		
        var cx = 0;		
        var cy = 0;		
        var cwidth = img.Width;		
        var cheight = img.Height;		
		break;
		
	case 3: // centre	
		var sr = img.Width / img.Height;
		var dr = new_width / new_height;	
		if (sr < dr) {	
			var r = img.Width / new_width;
			var cheight = new_height * r;
			var cy = Math.round((img.Height - cheight) / 2);
			var cwidth = img.Width;
			var cx = 0;
		} else {	
			var r = img.Height / new_height;
			var cwidth = new_width * r;
			var cx = Math.round((img.Width - cwidth) / 2);
			var cheight = img.Height;
			var cy = 0;
		}	
        var x = border + margin;		
        var y = border + margin;			
        var width = new_width;			
        var height = new_height;			
		break;	
        			
	case 4: // centre - top		
        var sr = img.Width / img.Height;								
        var dr = new_width / new_height;								
        if (sr < dr) {
            var r = img.Width / (new_width);								
            var cheight = new_height * r;		
            var cy = 0;								
            var cwidth = img.Width;								
            var cx = 0;								
        } else {
            var r = img.Height / new_height;								
            var cwidth = new_width * r;	
            var cx = Math.round((img.Width - cwidth) / 2);								
            var cheight = img.Height;								
            var cy = 0;								
		}						
        var x = border + margin;									
        var y = border + margin;								
        var width = new_width;								
        var height = new_height;								
		break;			
	case 5: // stretch		
        var x = border + margin;									
        var y = border + margin;									
        var width = new_width;								
        var height = new_height;								
        var cx = 0;								
        var cy = 0;								
        var cwidth = img.Width;								
        var cheight = img.Height;								
		break;	
    }	
	
    size.x = Math.round(x);								
    size.y = Math.round(y); 
    size.w = Math.round(width <= 0 ? 0 : width); 								
    size.h = Math.round(height <= 0 ? 0 : height); 	
    size.cx = Math.round(cx); 								
    size.cy = Math.round(cy);								
    size.cw = Math.round(cwidth);								
    size.ch = Math.round(cheight);								
    return size;	
}

function copy_files(select_file){
    var tmp_path;
    var tmp_files = [];
    var tmp_artist = meta_artist;
    var tmp_folder = ch(); 

    if (complete_path.indexOf('://') > 0 || !complete_path){
        tmp_path = fb.ProfilePath + "tmp_lastFm_img\\" + clean(meta_artist);
    } else {
        tmp_path = directory_path + "\\" + tmp_folder + "\\";
    }   
    
    var nl = "\" + chr(10) + \"";

    if (select_file == 0){
        tmp_files.push(img_file_names[img_selected]);
        var input_box_text = "Copy  " + nl + nl + get_fnext(tmp_files[0]) + nl + "file to";
    } else {
        tmp_files = img_file_names;
        var input_box_text = "Copy  " + nl + nl + tmp_artist + " * " + tmp_folder + ".jpg" + nl + "files to";
    }

    var string = input_box(input_box_text, "Foobar 2000", tmp_path);
    if (!/\S/.test(string)) copy_files();
    
    if (string){
        tmp_path = folder_exists(string);
        if (fso.FolderExists(tmp_path)) {
            copy_files_to_folder(tmp_path, tmp_files);
        }
    }
}

function copy_files_to_folder(path, files, folder){
    for (i in files) {
        try {
            fso.CopyFile(files[i], path  , 1);
        } catch(e) {};
    }
}

function input_box(prompt, caption, defaultval){
    return vbe.eval( "InputBox(\"" + prompt + "\",\"" + caption + "\",\"" + defaultval + "\")");
}

function clean_path_name(n) {
    if (!n) return;
    return n.replace(/[\/\:\*\?\"\<\>\|]/g,'');
}

function folder_exists(n) {
    var driver = fso.GetDriveName(n);
    if (!fso.DriveExists(driver)) {
        return "";
    } else {
        var p = "";
        var split_string = [];
        split_string = n.replace(/\\$/g, "").split("\\");

        for (var i = 1; i < split_string.length; i++) {
            p = p + clean_path_name(split_string[i]) + "\\";
            try {
                if(!fso.FolderExists(driver + "\\" + p)) fso.CreateFolder(driver + "\\" + p);
            } catch(e) {};
        }
        return driver + "\\" + p;
    }
}

function naturalSort(stringArray) {
    var xor = function(a, b) {
        return a ? !b : b;
    }
    var isDigit = function(chr) {
        var charCode = function(ch) {
            return ch.charCodeAt(0);
        };
        var code = charCode(chr);
        return (code >= charCode('0')) && (code <= charCode('9'));
    }
    var splitString = function(str) {
        var from = 0;   
        var index = 0;
        var count = 0;  
        var splitter = {};

        splitter.count = function () {
            return count;
        }
        splitter.next = function() {
            if (index === str.length) {
                return null;
            }
            while(++index) {
                var currentIsDigit = isDigit(str.charAt(index - 1));  
                var nextChar = str.charAt(index);
                var currentIsLast = (index === str.length);
                var isBorder = currentIsLast || xor(currentIsDigit, isDigit(nextChar));        
                if (isBorder) {
                var part = str.slice(from, index);
                    from = index;
                    count++;
                    return {
                        IsNumber: currentIsDigit,
                        Value: currentIsDigit ? Number(part) : part
                    }
                }
            } 
        } 
        return splitter;
    }
    var compareStrings = function(str1, str2) {
        var compare = function(a, b) {  
            return (a < b) ? -1 : (a > b) ? 1 : 0;
        }
        var splitter1 = splitString(str1);
        var splitter2 = splitString(str2);
        while (true) {
            var first = splitter1.next();
            var second = splitter2.next();
            if (null !== first && null !== second) {
                if (xor(first.IsNumber, second.IsNumber)) {
                    return first.IsNumber ? -1 : 1;        
                } else {                    
                    var comp = compare(first.Value, second.Value);    
                    if (comp != 0) {
                        return comp;
                    }
                }						
            } else {						
                return compare(splitter1.count(), splitter2.count());						
            }						
        }						
    }						
    var arr = stringArray;						
    return arr.sort(compareStrings);  						
}

//  Scroll

function scroll_check(){
    if (scroll >= 0){	
        scroll = 0;
    } else if (Math.abs(scroll) + text_rows_per_panel_height >= text_height){
        scroll = (text_height - text_rows_per_panel_height) * -1; 
    }

    !scroll_timer_on && text_scroll_timer();
}

function text_scroll_timer(){
    scroll_timer_on = true;
    scroll_timer && window.ClearInterval(scroll_timer);
    scroll_timer = window.SetInterval(function() {
        if (Math.abs(scroll - scroll_) > 0.1){	
            k = on_scrollbar_down ? 1.5 : (on_seekbar_down ? 2 : 2 + scroll_k); // 3
            
            scroll___ += (scroll - scroll___) / k ;			
            scroll__ += (scroll___ - scroll__) / k;		
            scroll_ += (scroll__ - scroll_) / k;
            
            if (!key_down) get_text_idx();
            get_selected_item();
            
            scroll_delta = Math.ceil(Math.abs(scroll_) / text_row_height) * text_row_height - Math.abs(scroll_);
        } else {
            window.ClearInterval(scroll_timer);
            scroll_ = scroll;
            scroll_timer_on = false;
            key_down = false;
        }
        
        wheel_id = 0;
        get_selected_item();
        
        window.RepaintRect(t_x, t_y - text_row_height, ww - t_x, wh);
    }, 40);
}

//  History_list

function add_name_to_history_list(name){
    if (!name) return;
    
    exist = false;
    var arr = create_history_array();

    for (var i = 0; i < arr.length; i++) {
        if (trim(arr[i]).toLowerCase() == trim(name).toLowerCase()){
            exist = true;
            break;
        }
    }

    if (!exist){
        try {
            file = fso.OpenTextFile(history_file_path, 8);
            file.WriteLine(trim(name));
            file.Close(); 
        } catch(e) {};        
    }
}

function del_history_list(){
    if (history.length) {
        try {
            file = fso.OpenTextFile(history_file_path, 2);
            file.Close(); 
        } catch(e) {};  
    }
    
    get_history();
}
         
function get_history(){
    scroll = scroll_ = scroll__ = scroll___ = 0;
    history = [];
    history_result = true;

    var arr = create_history_array();

    if (arr.length){
        for (var i = 0; i < arr.length; i++) {
            if (arr[i].substring(0, history_seach.length).toLowerCase() == history_seach.toLowerCase()){
                history.push(arr[i]);
                history_result = true;
            }
        }

        if (history.length == 0) {
            history = arr;
            history_result = false;
        }
    }

    get_text_arr(true);

    if (histity_list_edit){
        scroll = scroll_ = scroll__ = scroll___ = scroll_old; 
        text_idx = text_idx >= text_rows ? text_rows - 1 : text_idx;
        histity_list_edit = false; 
    } else {
        get_text_idx();
    }
    
    get_selected_item();
}

function del_history_item(){
    histity_list_edit = true; 
    
    if (Math.abs(scroll) + text_rows_per_panel_height == text_height && scroll < 0){
        scroll_old = scroll + text_row_height;
    } else {
        scroll_old = scroll;
    }
    
    var arr = create_history_array();
    
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == selected_item){
            arr.splice(i, 1);
        }
    } 
    
    try {
        file = fso.OpenTextFile(history_file_path, 2);
        if (arr.length){
            file.WriteLine(arr.join("\r\n"));
        }
        file.Close(); 
    } catch(e) {};  

    get_history();
}

function create_history_array(){ 
    check_file(history_file_path);
    var arr = [];
    
    if (fso.FileExists(history_file_path)){
        arr = utils.ReadTextFile(history_file_path).split("\r\n").sort();

        for (var i = arr.length; i >= 0; i--) {
            if (!arr[i] || !/\S/.test(arr[i])) arr.splice(i, 1);
        }
    }
    
    return arr.length ? arr : [];
}

function get_text_idx(){
    text_idx = Math.round(Math.floor((pos_y - t_y) / text_row_height) + Math.abs(scroll) / text_row_height);
    text_idx = Math.max(0 + (Math.abs(scroll) / text_row_height), Math.min(text_idx, text_rows_per_panel - 1 + (Math.abs(scroll) / text_row_height)));
}

function get_selected_item() {
    selected_item = selected_item_rows[text_idx];
    selected_item_rows_idx = [];
    
    if (selected_item_rows.length > 1){
        for (var j = 0; j < selected_item_rows.length; j++) {
            if (selected_item_rows[j]) {
            
                if (t_y + (j * text_row_height) - Math.abs(scroll) > 0){
                    window.RepaintRect(t_x, t_y + (j * text_row_height) - Math.abs(scroll), text_row_width, text_row_height);
                }
            
                if (selected_item_rows[j] == selected_item) {
                    selected_item_rows_idx.push(j);
                } 
            } 
        }
    }
}

//  Remap name

function remap_file_path(n){
    if (!n) return "";
    return script_path + "remap_" + n + ".txt";
}

function v1(n){
    if (!n) return "";
    return n.replace(/(.*?)\*.*/g, "$1");
}

function v2(n){
    if (!n) return "";
    return n.replace(/.*\*(.*)\*.*/g, "$1");
}

function v3(n){
    if (!n) return;
    return n.replace(/.*\*(.*)/g, "$1");
}

function remap_artist(artist){
    if (!artist) return "";
    var tmp = "";
    var arr = create_remap_array("artist");
    for (var i = 0; i < arr.length; i++) {
        if (trim(v1(arr[i])).toLowerCase() == trim(artist).toLowerCase()) {
            tmp = v3(arr[i]);
            break;
        }
    }
    return tmp ? trim(tmp) : trim(artist);
}

function remap_album(artist, album){
    if (!artist || !album) return "";
    var tmp = "";
    var arr = create_remap_array("album");
    for (var i = 0; i < arr.length; i++) {
        if (trim(v1(arr[i])).toLowerCase() == trim(artist).toLowerCase() && trim(v2(arr[i])).toLowerCase() == trim(album).toLowerCase()) {
            tmp = v3(arr[i]);
            break;
        }
    }
    return tmp ? trim(tmp) : trim(album);
}

function create_remap_array(name){
    path = remap_file_path(name);
    
    check_file(path);
    var arr = [];
    
    if (fso.FileExists(path)){
        arr = utils.ReadTextFile(path).split("\r\n").sort();
        for (var i = arr.length; i >= 0; i--) {
            if (!arr[i] || !/\S/.test(arr[i])) arr.splice(i, 1);
        }
    }
    return arr.length ? arr : [];
}

function edit_remap_list(artist, album, name){
    if (name == "artist" && !artist) return;
    if (name == "album" && (!artist || !album)) return;
    
    c_name = "";
    n_name = "";
    prompt_text = ""

    var arr = create_remap_array(name);

    for (var i = 0; i < arr.length; i++) {
        if (name == "album"){
            if (trim(v1(arr[i])).toLowerCase() == artist.toLowerCase() && trim(v2(arr[i])).toLowerCase() == album.toLowerCase()) {        
                c_name = trim(v2(arr[i]));
                n_name = trim(v3(arr[i]));
                break;
            }
        }
        
        if (name == "artist"){
            if (trim(v3(arr[i])).toLowerCase() == artist.toLowerCase()) {
                c_name = trim(v1(arr[i]));
                n_name = trim(v3(arr[i]));
                break;
            }
        }
    }
    
    if (c_name) { 
        prompt_text = "(edit name or enter empty string to delete)";
    }
    
    if (!c_name) { 
        if (name == "album"){
            c_name = album ? album : "...";
        }
        
        if (name == "artist"){
            c_name = artist ? artist : "...";
        }

        n_name = c_name;
        prompt_text = "(enter new name)";
    }
    
    var nl = "\" + chr(10) + \"";
    var prompt = "Remap" + nl + c_name + nl + nl + "by" + nl + prompt_text;
    n_name = input_box(prompt, "Foobar 2000", n_name, 1);  

    if (typeof(n_name) != "undefined"){
        if (!/\S/.test(n_name) && n_name != "") {
            edit_remap_list(artist, album, name);
        }

        if (n_name == "" || (trim(n_name) == c_name)){
            del_remapped_name(artist, album, c_name, name);
        }

        if (/\S/.test(n_name) && n_name && (trim(n_name) != c_name)){
            del_remapped_name(artist, album, c_name, name);
            
            if (name == "album"){
                arr.push(artist + "*" + c_name + "*" + trim(n_name));
            }
                
            if (name == "artist"){
                arr.push(c_name + "*" + trim(n_name));
            }
            edit_remap_file(arr.sort(), name);
        }
        refresh_data = true;
        on_metadb_changed();
    }
}

function del_remapped_name(artist, album, c_name, name){
    var arr = create_remap_array(name);

    for (var i = arr.length; i >= 0; i--) {
        if (v1(arr[i])) {
            
            if (name == "album"){
                if (trim(v1(arr[i])).toLowerCase() == trim(artist).toLowerCase() && trim(v2(arr[i])).toLowerCase() == trim(c_name).toLowerCase()) {
                    arr.splice(i, 1);
                    break;
                }
            }
            
            if (name == "artist"){
                if (trim(v1(arr[i])).toLowerCase() == trim(c_name).toLowerCase()) {
                    arr.splice(i, 1);
                    break;
                }
            }
        }
    } 
    edit_remap_file(arr, name);
}

function edit_remap_file(arr, name){
    try {
        file = fso.OpenTextFile(remap_file_path(name), 2);
        if (arr.length){
            file.WriteLine(arr.join("\r\n"));
        }
        file.Close(); 
    } catch(e) {};  
}

function remap_name(){
    if (ch() == "artist" || ch() == "popular_albums" || ch() == "similar" || ch() == "title" || ch() == "lyrics"){
        return "artist";
    } else if (ch() == "album"){  
        return "album";
    }
}

function ch(){
    switch(data_main) {                                                                                        
    case 0:          
        return "artist"; break;                                                                                 
    case 1:                                                                        
        switch(data_sub) {                                                                                       
        case 0:  
            return "popular_albums"; break;              
        case 1:                                                                                
            return "similar"; break;              
        case 2:  
            return "album"; break;
        case 3: 
            return "title"; break;
        case 4:
            return "lyrics"; break;
        }                                                                                            
        break;                                                                                 
    }  
}

function help(){
    var button_type = 0x0;
    var icon_type = 0x20;

    switch (lang_arr[lang_idx]) {
    case "ru":
        var title = "     ";
        var txt = 
        '-   -    (  + Shift)      ");' + '\n\n' + 
        '-   - Shift         (  -  Properties,      ");' + '\n\n' +     
        '-   -     ;' + '\n\n' + 
        '-  /   -    ' + '\n\n' + 
        '-     - Ctrl +   ;' + '\n\n' + 
        '-   -   ;' + '\n\n' + 
        '-     - Shift     ;' + '\n\n' + 
        '- : "", " ", " ", "" (,   ), "  "  " ()" -        ;' + '\n\n' + 
        '-  /   "Lock" -     ;' + '\n\n' +  
        '-  /     - "Main menu setting";' + '\n\n' +  
        '-   -  "Properties".' 
        break
    default:
        var title = "Keyboard shortcut and settings help";
        var txt = 
        '- select language - double click LMB (or LMB + Shift) over the text or through the menu");' + '\n\n' +
        '- font size - Shift and WHEEL over the text or text headings (font name - menu "Properties", style or alignment through the menu");' + '\n\n' +
        '- text scroll - WHEEL over the text, Up, Down, Page Up, Page Down, Home or End buttons' + '\n\n' +
        '- move the text - while pressing the LMB over the text;' + '\n\n' +
        '- hide / restore text - double-click MMB;' + '\n\n' +
        '- the background transparency under the text - Ctrl + WHEEL over the text;' + '\n\n' +
        '- change the image - the WHEEL over the image or Left \ Right buttons;' + '\n\n' +
        '- set the interval of the image change - Shift and the WHEEL over the image;' + '\n\n' +
        '- select Artist, Top Albuums, Similar Artist, Album info, Track Info or Lyrics - Double-click on the LMB over the image or through the menu ; ' + '\n\n' +
        '- On / Off "Lock" mode - Double-click on the LMB over the text header;' + '\n\n' +
        '- enable / disable the context menu items - "Main menu setting".' + '\n\n' +
        '- additional settings - menu "Properties" .'
        break
    }
    
    var btn = WshShell.Popup(txt, 0, title, button_type + icon_type);
}

function get_lastFm_artist(artist){	
    var xmlhttp12 = new ActiveXObject("Microsoft.XMLHTTP");   						
    url12 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(artist));  
    xmlhttp12.open("GET", url12, true );  
    xmlhttp12.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp12.send(null);     
    xmlhttp12.onreadystatechange = function () { 
        if (xmlhttp12.readyState == 4) { 
            if (xmlhttp12.status == 200) { 
                doc.open();		
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp12.responsetext;
                var h1 = div.getElementsByTagName("h1");	                
                
                var name = "";
                
                for (i = 0; i < h1.length; i++) {	
                    if (h1[i].className == "header-new-title") {
                        name = h1[i].innerHTML.replace(/&amp;/g, "And");
                    }  
                }

                if (name){
                    history_on = false;
                	data_main = 0;
                    tf_artist = name;
                    tf_album = "";
                    tf_title = "";
                	on_metadb_changed();
                }

                doc.close();
            } else {
                history_query = false;
                history_seach = artist;
                get_history();
            }
        }
    }
}

function get_lastFm_meta_artist_img(img_refresh, path, artist){
    var xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");   						
    var url1 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(artist) + "/+images");
    xmlhttp1.open("GET", url1, true ); 
    xmlhttp1.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");	
    xmlhttp1.send(null);    
    xmlhttp1.onreadystatechange = function () { 
        if (xmlhttp1.readyState == 4) {
            if (xmlhttp1.status == 200) {  
                doc.open();     
                var div = doc.createElement("div");
                div.innerHTML = xmlhttp1.responsetext;
                var d = div.getElementsByTagName("div");	
                var img = div.getElementsByTagName("img");
                
                no_img_msg = "";

                for (i = 0; i < d.length; i++) {  							
                    if (d[i].className == "no-data-message"){   // "We don't have any photos for this artist yet."  							
                       no_img_msg = d[i].innerText + "\n\n";
                    }							
                }

                var img_urls = [];
                
                for (i = 0; i < img.length; i++) {   
                    if (img[i].src.indexOf("avatar170s") > 0) {
                        img_urls.push(img[i].src.replace("avatar170s", quality[quality_idx][1]));
                    }  
                }
                
                for (i = 0; i < Math.min(img_urls.length, limit); i++) {  
                    var img_file = path + "\\" + clean(artist) + "_"  + i + "_artist.jpg";
                    
                    if (!fso.FileExists(img_file)){
                        WshShell.Run(vbs + " " + img_urls[i] + " " + "\"" + img_file + "\"", 0, false);
                    }	
                }
                
                doc.close();
            }
            get_files_if_loaded(img_refresh, path, artist);
        } 						
    }     						
}	

function get_lastFm_popular_albums_img(img_refresh, path, artist){	
    var xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");   						
    var url2 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(artist) + "/+albums"); 
    xmlhttp2.open("GET", url2, true );  
    xmlhttp2.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp2.send(null);     
    xmlhttp2.onreadystatechange = function () { 
        if (xmlhttp2.readyState == 4) { 
            if (xmlhttp2.status == 200) {  
                doc.open();     
                var div = doc.createElement("div");
                div.innerHTML = xmlhttp2.responsetext;
                var img = div.getElementsByTagName("img");
                 
                var urls = [];
                var img_urls = [];
                var tmp_album_name = [];
                var album_name = [];
 
                for (i = 0; i < img.length; i++) {
                    if (img[i].alt.indexOf("Avatar for") < 0){
                        if (img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/300x300") == 0 || img[i].src.indexOf("https://lastfm.freetls.fastly.net/i/u/300x300") == 0){    
                            urls.push(img[i].src);
                            tmp_album_name.push(img[i].alt);
                        }
                    }
                }
                
                for (i = 0; i < urls.length; i++) {     // if image exist 
                    if (urls[i].indexOf("c6f59c1e5e7240a4c0d427abd71f3dbb") < 0 && urls[i].indexOf("2a96cbd8b46e442fc41c2b86b821562f") < 0) {	
                        img_urls.push(urls[i].replace("300x300", quality[quality_idx][1]));
                        album_name.push(tmp_album_name[i]);
                    }						
                }
                     
                for (i = 0; i < Math.min(img_urls.length, limit); i++) {  
                    utils.WriteINI( path + "\\" + clean(artist) + "_album_info.ini", data_sub_value[data_sub][2] + " : name", i, album_name[i]);	

                    var img_file = path + "\\" + clean(artist) + "_"  + clean(album_name[i]) + ".jpg";   

                    if (!fso.FileExists(img_file)){
                        WshShell.Run(vbs + " " + img_urls[i] + " " + "\"" + img_file + "\"", 0, false);
                    }
                } 
                
                doc.close();
            }
            get_files_if_loaded(img_refresh, path, artist);
        } 				
    }   
}	

function get_lastFm_similar_img(img_refresh, path, artist){	
    var xmlhttp5 = new ActiveXObject("Microsoft.XMLHTTP");   						
    var url5 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(artist) + "/+similar"); 
    xmlhttp5.open("GET", url5, true );  
    xmlhttp5.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");	
    xmlhttp5.send(null);     					
    xmlhttp5.onreadystatechange = function () { 					
        if (xmlhttp5.readyState == 4) { 					
            if (xmlhttp5.status == 200) {  					
                doc.open();     					
                var div = doc.createElement("div");					
                div.innerHTML = xmlhttp5.responsetext;
                var p = div.getElementsByTagName("p");	 
                var a = div.getElementsByTagName("a");	
                var img = div.getElementsByTagName("img");	

                var urls = [];
                var img_urls = [];
                var tmp_similar_artist = [];
                var similar_artist = [];

                for (i = 0; i < a.length; i++) {  							
                    if (a[i].className == "link-block-target"){    // similar artist names 							
                        tmp_similar_artist.push(a[i].innerHTML.replace(/(&amp;)/g,'&'));
                    }							
                } 
          
                var info =[], color = [], font = []; 
                var tmp_info =[]; 

                for (i = 0; i < p.length; i++) {  							
                    if (p[i].className == "similar-artists-item-aux-text similar-artists-item-listeners"){ 						
                        tmp_info.push(p[i].innerHTML.replace(/,/g, " "));
                    }							
                } 
   
                for (i = 0; i < img.length; i++) {
                    if (img[i].src.indexOf("https://lastfm-img2.akamaized.net/i/u/300x300") == 0 || img[i].src.indexOf("https://lastfm.freetls.fastly.net/i/u/300x300") == 0){  
                        urls.push(img[i].src);
                    }
                }

                for (i = 0; i < urls.length; i++) {     // if image exist 
                    if (urls[i].indexOf("c6f59c1e5e7240a4c0d427abd71f3dbb") < 0 && urls[i].indexOf("2a96cbd8b46e442fc41c2b86b821562f") < 0) {	
                        img_urls.push(urls[i].replace("300x300", quality[quality_idx][1]));
                        similar_artist.push(tmp_similar_artist[i]);
                        info.push(tmp_info[i]);
                    }						
                }
                
                for (i = 0; i < Math.min(img_urls.length, limit); i++) { 
                    utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", data_sub_value[data_sub][2] + " : name", i, similar_artist[i]); 							
                    utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", data_sub_value[data_sub][2] + " : info : " + lang_arr[lang_idx], i, info[i]);

                    var img_file = path + "\\" + clean(artist) + "_"  + i + "_" + data_sub_value[data_sub][2] + ".jpg";
                        
                    if (!fso.FileExists(img_file )){
                        WshShell.Run(vbs + " " + img_urls[i] + " " + "\"" + img_file + "\"", 0, false);
                    }
                } 
                
                doc.close();
            }
            get_files_if_loaded(img_refresh, path, artist, "", "");
        } 					
    }     					
}

function get_lastFm_meta_album_img(img_refresh, path, artist, album){
    var xmlhttp6  = new ActiveXObject("Microsoft.XMLHTTP");   
    var url6 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(artist) + "/" + encodeURIComponent(album));  
    xmlhttp6.open("GET", url6, true ); 
    xmlhttp6.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp6.send(null);     
    xmlhttp6.onreadystatechange = function () { 
        if (xmlhttp6.readyState == 4) { 
            if (xmlhttp6.status == 200) { 
                doc.open();     
                var div = doc.createElement("div");
                div.innerHTML = xmlhttp6.responsetext;
                var li = div.getElementsByTagName("li");
                var h1 = div.getElementsByTagName("h1");
                var h4 = div.getElementsByTagName("h4");
                var abbr = div.getElementsByTagName("abbr");
                var dt = div.getElementsByTagName("dt");                                
                var dd = div.getElementsByTagName("dd");              
                var img = div.getElementsByTagName("img");

                var info = [], color = [], font = [];
                
                var tag = "";

                for (i = 0; i < li.length; i++) {						
                    if (li[i].className == "tag") {
                        tag = tag + li[i].innerText + "; ";
                    }
                } 

                if (tag) {
                    tag = tag.substring(0, tag.length - 2);
                    info.push(tag, "");
                    color.push("t_color", "");
                    font.push("t2_font", "");
                }              

                var tmp_info_1 = [], tmp_info_2 = [];
                
                for (i = 0; i < h4.length; i++) {
                    if (h4[i].className == "header-metadata-tnew-title") {  // "listeners"	"scrobbles"
                        tmp_info_1.push(h4[i].innerText);
                    }
                }

                for (i = 0; i < abbr.length; i++) {	
                    if (abbr[i].className == "intabbr js-abbreviated-counter") {    // 13,294,523  512,404
                        tmp_info_2.push(abbr[i].title.replace(/,/g, " "));
                    }
                }  

                for (i = 0; i < tmp_info_1.length / 2; i++) {
                    info.push(tmp_info_1[i], tmp_info_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font"); 
                } 

                if (tmp_info_1.length){      // empty line
                    info.push("");
                    color.push("");
                    font.push("");
                }

                var tmp_info_1 = [], tmp_info_2 = [];
                
                for (i = 0; i < dt.length; i++) {						
                    if (dt[i].className == "catalogue-metadata-heading") {  // "length",  "release date"
                        if (dt[i].innerText) tmp_info_1.push(dt[i].innerText);
                    }
                }

                for (i = 0; i < dd.length; i++) { 
                    if (dd[i].className == "catalogue-metadata-description"){   // 8 tracks, 33:00,  5 July 1968
                        if (dd[i].innerText) tmp_info_2.push(dd[i].innerText);
                    }
                }               
                
                for (i = 0; i < tmp_info_1.length / 2; i++) {
                    info.push(tmp_info_1[i], tmp_info_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font");
                }  
                
                var img_urls = [];
                var album_name = "";
                
                for (i = 0; i < h1.length; i++) {
                    if (h1[i].className == "header-new-title"){ 
                        album_name = h1[i].innerText;
                        break;
                    }
                }

                for (i = 0; i < img.length; i++) {
                    if (img[i].alt == album_name) {
                        img_urls.push(img[i].src.replace("500x500", quality[quality_idx][2]));
                        break;
                    }
                } 
                
                if (img_urls.length) {
                    utils.WriteINI( path + "\\" + clean(artist) + "_album_info.ini", clean_ini(clean(album)), lang_arr[lang_idx], info.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_album_info.ini", clean_ini(clean(album)), lang_arr[lang_idx] + "_c", color.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_album_info.ini", clean_ini(clean(album)), lang_arr[lang_idx] + "_f", font.join("*"));

                    var img_file = path + "\\" + clean(artist) + "_" + clean(album) + ".jpg";  

                    if (!fso.FileExists(img_file)){
                        WshShell.Run(vbs + " " + img_urls[0] + " " + "\"" + img_file + "\"", 0, false);
                    }
                }

                doc.close();
            }
            get_files_if_loaded(img_refresh, path, artist, album);
        } 
    } 
}

function get_lastFm_meta_title_img(img_refresh, path, artist, album, title){
    var q1 = encodeURIComponent(artist) + "/";
    var q2 = album ? encodeURIComponent(album).replace("%2B", "%252B") + "/" : "_/";
    var q3 = title ? encodeURIComponent(title) : "";
    xmlhttp7 = new ActiveXObject("Microsoft.XMLHTTP");
    url7 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + q1 + q2 + q3);
    xmlhttp7.open("GET", url7, true);							
    xmlhttp7.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp7.send(null);							
    xmlhttp7.onreadystatechange = function () {							
        if (xmlhttp7.readyState == 4) {							
            if (xmlhttp7.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp7.responsetext;
                var h3 = div.getElementsByTagName("h3");
                var h4 = div.getElementsByTagName("h4");
                var abbr = div.getElementsByTagName("abbr");
                var ddiv = div.getElementsByTagName("div");	
                var img = div.getElementsByTagName("img");

                var album_name = "";
                var info = [], color = [], font = []; 
                                
                for (i = 0; i < h3.length; i++) {		 // "from the album"				 			
                    if (h3[i].className == "text-18") {
                        _name = h3[i].innerText;						
                        break;						
                    }
                }
                
                for (i = 0; i < h4.length; i++) {		 // album name				
                    if (h4[i].className == "source-album-name") {
                        album_name = h4[i].innerText;						
                        album_name && info.push(_name, album_name, "");
                        album_name && color.push("h1_color", "t_color", "");
                        album_name && font.push("t2_font", "t_font", "");
                        break;						
                    }
                }
                
                var tmp_info_1 = [], tmp_info_2 = [];
         
                for (i = 0; i < h4.length; i++) {
                    if (h4[i].className == "header-metadata-tnew-title") {    // "listeners",	"scrobbles"
                        tmp_info_1.push(h4[i].innerText);
                    }
                }
               
                for (i = 0; i < abbr.length; i++) {
                    if (abbr[i].className == "intabbr js-abbreviated-counter") {   // 2,426,608  413,322
                        tmp_info_2.push(abbr[i].title.replace(/,/g, " "));
                    }
                }

                for (i = 0; i < tmp_info_1.length / 2; i++) {
                    info.push(tmp_info_1[i], tmp_info_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font"); 
                } 

                no_img_msg = "";
                
                for (i = 0; i < ddiv.length; i++) {						
                    if (ddiv[i].className == "source-album-nodata") {   // "We dont have an album for this track yet."
                        no_img_msg = ddiv[i].firstChild.innerText + "\n\n";
                        break;						
                    }
                }
                
                var img_urls = [];

                for (i = 0; i < img.length; i++) {
                    if (img[i].alt == album_name) {
                        img_urls.push(img[i].src.replace("300x300", quality[quality_idx][2]));
                        break;
                    }
                } 
                
                if (img_urls.length) {
                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "album", album_name);
                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), lang_arr[lang_idx], info.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), lang_arr[lang_idx] + "_c", color.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), lang_arr[lang_idx] + "_f", font.join("*"));

                    var img_file = path + "\\" + clean(artist) + "_" + clean(album_name) + ".jpg";

                    if (!fso.FileExists(img_file)){
                        WshShell.Run(vbs + " " + img_urls[0] + " " + "\"" + img_file + "\"", 0, false);
                    }
                }
                
                doc.close();
            }
            get_files_if_loaded(img_refresh, path, artist, album_name, title);
        }
    }						
}

function get_lastFm_bio_text(path, file, artist){
    xmlhttp3 = new ActiveXObject("Microsoft.XMLHTTP");					
    url3 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(artist) + "/+wiki");	
    xmlhttp3.open("GET", url3, true);					
    xmlhttp3.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp3.send(null);							
    xmlhttp3.onreadystatechange = function () {	
        if (xmlhttp3.readyState == 4) {	
            if (xmlhttp3.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp3.responsetext;
                var li = div.getElementsByTagName("li");
                var ddiv = div.getElementsByTagName("div");	
                
                var active = [];
                var members = [];

                for (i = 0; i < li.length; i++) {	
                    if (li[i].className == "factbox-item") { 
                        if (li[i].innerText) {
                            factbox = li[i].innerHTML.replace(/\n+/gi, "").replace(/<\/H4.*<P>/gi, ": ").replace(/<\/P>/gi, "\n").replace(/<H4.*>/gi, "").replace(/^\n+|\n+$/g, ""); 
                            factbox ? active.push(factbox) : "";
                        }
                    }                    
                }

                years_active = active.join("\n");
                utils.WriteINI( path + "\\" + clean(meta_artist) + "_artist_info.ini", clean_ini(clean(artist)) + " : years active", lang_arr[lang_idx], active.join("*"));

                //members = li[i].innerHTML.replace(/<\/UL>.*/gi, "").replace(/<UL.*>/gi, "").replace(/<LI><SPAN>(.*)<\/SPAN>(.*)<\/LI>/gi, "$1 $2, "); 
                //factbox = ttt.replace(/<\/H4>/gi, " : ").replace(/<H4.*>/gi, "").replace(/<P>(.*)<\/P>/gi, "$1");                        

                text = "";							
                var save_text = false;

                for (i = 0; i < ddiv.length; i++) {	
                    if (ddiv[i].className == "wiki") {							
                        t = ddiv[i].innerHTML;                  // bio text or "We don't have a wiki here yet..."
                        save_text = t.indexOf('wiki-content') > 0 ? true : false;		
                        text = strip_tags(t);	
                        break;							
                    } 							
                } 

                text = no_img_msg + text;
                if (save_text) save_txt_file(text, file);
 
                doc.close();
            } else {
                logo_img = marvin_img;
                text = "http: error";
            }
            if(!text) text = no_text_found(lang_arr[lang_idx]);
            get_text_arr(true);
        }
    }
}

function get_lastFm_artist_info_text(path, file, artist){
    var xmlhttp9 = new ActiveXObject("Microsoft.XMLHTTP");   
    var url9 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(artist)); 
    xmlhttp9.open("GET", url9, true ); 
    xmlhttp9.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp9.send(null);     
    xmlhttp9.onreadystatechange = function () {
        if (xmlhttp9.readyState == 4) {
            if (xmlhttp9.status == 200) { 
                doc.open();     
                var div = doc.createElement("div");
                div.innerHTML = xmlhttp9.responsetext;
                var p = div.getElementsByTagName("p");
                var a = div.getElementsByTagName("a");
                var li = div.getElementsByTagName("li");
                var h4 = div.getElementsByTagName("h4");
                var abbr = div.getElementsByTagName("abbr");
                var a = div.getElementsByTagName("a");
                
                var info =[], color = [], font = []; 
                
                ////////////////////////////////////////////////////////////////////////////////////

                var tmp_text = "";
                var tmp_value = "";
                var rank_text = [];
                var rank_color = [];
                var rank_font = [];
                
                for (i = 0; i < p.length; i++) {
                    if (p[i].className.replace(/[\s]/g, "") == "tooltip-dark header-new-chart-position-tooltip".replace(/[\s]/g, "")) {
                        tmp_text = trim(p[i].innerText.replace(/\./g, ""));
                    }
                } 
                
                for (i = 0; i < a.length; i++) {
                    if (a[i].className.replace(/[\s]/g, "") == "header-new-chart-position-number disclose-trigger".replace(/[\s]/g, "")) {
                        tmp_value = trim(a[i].innerText);
                    }
                }           

                if (tmp_text && tmp_value) {
                    rank_text.push(tmp_text, tmp_value, "", "");
                    rank_color.push("h1_color", "t_color", "", "");
                    rank_font.push("t2_font", "t_font", "", "");

                    utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_rank", rank_text.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_rank_c", rank_color.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_rank_f", rank_font.join("*"));
                } 

                ////////////////////////////////////////////////////////////////////////////////////
                
                var tag = "";

                for (i = 0; i < li.length; i++) {						
                    if (li[i].className == "tag") {     //  classic rock rock southern rock 60s folk 70s ........
                        tag = tag + li[i].innerText + "; ";
                    }
                } 

                if (tag) {
                    tag = tag.substring(0, tag.length - 2);
                    info.push(tag, "");
                    color.push("t_color", "");
                    font.push("t2_font", ""); 
                } 
 
                ////////////////////////////////////////////////////////////////////////////////////
                
                var tmp_info_1 = [], tmp_info_2 = [];;

                for (i = 0; i < h4.length; i++) {
                    if (h4[i].className == "header-metadata-tnew-title") {    // "listeners"	"scrobbles"
                        tmp_info_1.push(h4[i].innerText);
                    }
                }

                for (i = 0; i < abbr.length; i++) {
                    if (abbr[i].className == "intabbr js-abbreviated-counter") {     // 57,404,270, 2,314,768
                        tmp_info_2.push(abbr[i].title.replace(/,/g, " "));
                    }
                } 

                for (i = 0; i < tmp_info_1.length / 2; i++) {
                    info.push(tmp_info_1[i], tmp_info_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font"); 
                } 

                if (tmp_info_1.length) {
                    info.push("");
                    color.push("");
                    font.push("");  
                }

                ////////////////////////////////////////////////////////////////////////////////////
                
                var tmp_info_1 = [], tmp_info_2 = [];
                
                
                for (i = 0; i < h4.length; i++) {						
                    if (h4[i].className == "artist-header-featured-items-item-header") {    // "latest release", "popular this week"
                        tmp_info_1.push(h4[i].innerText);
                    }
                }

                for (i = 0; i < a.length; i++) {						
                    if (a[i].className == "link-block-target") {      // Live At Woodstock, Fortunate Son, 
                        tmp_info_2.push(a[i].innerText);
                    }
                } 

                utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), "latest_release", tmp_info_2[0]);
                utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), "popular_this_week", tmp_info_2[1]);

                for (i = 0; i < tmp_info_1.length; i++) {
                    info.push(tmp_info_1[i], tmp_info_2[i]);
                    color.push("h1_color", "t_color");
                    font.push("t2_font", "t_font"); 
                } 

                utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx], info.join("*"));
                utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_c", color.join("*"));
                utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), lang_arr[lang_idx] + "_f", font.join("*"));
                
                doc.close();
            }
            get_text(path, artist);
        }
    }     
}
							
function get_lastFm_album_text(path, file, artist, album){	
    xmlhttp4 = new ActiveXObject("Microsoft.XMLHTTP");							
    url4 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(artist) + "/" + encodeURIComponent(album).replace("%2B", "%252B") + "/+wiki");
    xmlhttp4.open("GET", url4, true);							
    xmlhttp4.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp4.send(null);							
    xmlhttp4.onreadystatechange = function () {							
        if (xmlhttp4.readyState == 4) {							
            if (xmlhttp4.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp4.responsetext;							
                var div = div.getElementsByTagName("div");	
                
                text = "";						
                var save_text = false;
                						
                for (i = 0; i < div.length; i++) {						
                    if (div[i].className == "wiki") {
                        t = div[i].innerHTML;
                        save_text = t.indexOf('wiki-content') > 0 ? true : false;						
                        text = strip_tags(t);						
                        break;						
                    } 						
                }
                
                text = no_img_msg + text;
                if (save_text) save_txt_file(text, file);

                doc.close();
            } else {
                logo_img = marvin_img;
                text = "http: error";
            }
            if(!text) text = no_text_found(lang_arr[lang_idx]);
            get_text_arr(true);
        }
    }						
}						

function get_lastFm_meta_title_text(path, file, artist, album, title){
    var q1 = encodeURIComponent(artist) + "/";
    var q2 = album ? encodeURIComponent(album).replace("%2B", "%252B") + "/" : "_/";
    var q3 = title ? encodeURIComponent(title) : "_";
    xmlhttp8 = new ActiveXObject("Microsoft.XMLHTTP");							
    url8 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + q1 + q2 + q3 + "/+wiki");
    xmlhttp8.open("GET", url8, true);							
    xmlhttp8.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp8.send(null);							
    xmlhttp8.onreadystatechange = function () {							
        if (xmlhttp8.readyState == 4) {							
            if (xmlhttp8.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp8.responsetext;							
                var div = div.getElementsByTagName("div");
                
                text = "";						
                var save_text = false;

                for (i = 0; i < div.length; i++) {						
                    if (div[i].className == "wiki") {						
                        t = div[i].innerHTML;	
                        save_text = t.indexOf('wiki-content') > 0 ? true : false;						
                        text = strip_tags(t);							
                        break;						
                    } 						
                } 

                text = no_img_msg + text;
                if (save_text) save_txt_file(text, file);

                doc.close();
            } else {
                logo_img = marvin_img;
                text = "http: error";
            }
            if(!text) text = no_text_found(lang_arr[lang_idx]);
            get_text_arr(true);
        }
    }						
}

function get_domain(url){
    if (!url) return;
    return url.replace(/.*\/{2}/g, "").replace(/\/.*/g, ""); 
}

function metrolyrics_query(str){
    if (!str) return;
    str = str.toLocaleLowerCase();
    str = str.replace(/&/g, "and").replace(/\s/g, "-").replace(/\'/g, "");
    return str;
}

function get_metrolyrics_meta_lyrics_text(path, file, artist, title){
    xmlhttp9 = new ActiveXObject("Microsoft.XMLHTTP");	
    url9 = ("http://www.metrolyrics.com/" + metrolyrics_query(title) + "-lyrics-" + metrolyrics_query(artist) + ".html");
    xmlhttp9.open("GET", url9, true);							
    xmlhttp9.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp9.send(null);							
    xmlhttp9.onreadystatechange = function () {							
        if (xmlhttp9.readyState == 4) {	
            if (xmlhttp9.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp9.responsetext;							
                var p = div.getElementsByTagName("p");
                
                var t = "";	
                var tmp = [];
                var info = [], color = [], font = []; 
                
                for (i = 0; i < p.length; i++) {	
                    if (p[i].className == "verse") {
                        tmp.push(p[i].innerHTML);
                    } 						
                } 

                t = strip_tags(tmp.join("\n\n"));
                
                if (t){
                    info.push(get_domain(url9));
                    color.push("h1_color");
                    font.push("t2_font");
                
                    info_text = info;
                    info_text_color = color;
                    info_text_font = font;

                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "lyrics", info.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "lyrics_c", color.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "lyrics_f", font.join("*"));
                
                    text = t; 
                    save_txt_file(t, file);
                    get_text_arr(true);
                }
                
                doc.close();
            }
            if(!text) get_azlyrics_meta_lyrics_text(path, file, artist, title)
        }
    }						
}

function azlyrics_query(str){
    if (!str) return;
    str = str.toLocaleLowerCase();
    str = str.replace(/&/g, "and").replace(/\W/g, "");
    return str;
}

function get_azlyrics_meta_lyrics_text(path, file, artist, title){
    xmlhttp10 = new ActiveXObject("Microsoft.XMLHTTP");
    url10 = "https://www.azlyrics.com/lyrics/" + azlyrics_query(artist.replace(/^the/gi, "")) + "/" + azlyrics_query(title) + ".html"	
    xmlhttp10.open("GET", url10, true);							
    xmlhttp10.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");							
    xmlhttp10.send(null);							
    xmlhttp10.onreadystatechange = function () {							
        if (xmlhttp10.readyState == 4) {							
            if (xmlhttp10.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp10.responsetext;							
                var h = div.getElementsByTagName("div");
                
                var t = "";
                var info = [], color = [], font = []; 
                      
                for (i = 0; i < h.length; i++) {	
                    if (h[i].className == "") {
                        if (h[i].innerText) t = (h[i].innerText);
                    }
                }

                if (t) {
                    info.push(get_domain(url10));
                    color.push("h1_color");
                    font.push("t2_font");
                
                    info_text = info;
                    info_text_color = color;
                    info_text_font = font;

                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "lyrics", info.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "lyrics_c", color.join("*"));
                    utils.WriteINI( path + "\\" + clean(artist) + "_title_info.ini", clean_ini(clean(title)), "lyrics_f", font.join("*"));
                
                    text = t; 
                    save_txt_file(t, file);
                }
           
                doc.close();
            } else {
                logo_img = marvin_img;
                text = "http: error";
            }
            if(!text) text = no_text_found(lang_arr[lang_idx]);
            get_text_arr(true);
        }
    }						
}

function get_artist_external_links(path, artist){		
    xmlhttp11 = new ActiveXObject("Microsoft.XMLHTTP");					
    url11 = ("https://www.last.fm/" + lang_query(lang_idx) + "music/" + encodeURIComponent(artist));
    xmlhttp11.open("GET", url11, true);					
    xmlhttp11.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
    xmlhttp11.send(null);							
    xmlhttp11.onreadystatechange = function () {							
        if (xmlhttp11.readyState == 4) {							
            if (xmlhttp11.status == 200) {							
                doc.open();							
                var div = doc.createElement("div");							
                div.innerHTML = xmlhttp11.responsetext;
                var a = div.getElementsByTagName("a");	

                var tmp_data = [];
                var data = [];
                             
                for (i = 0; i < a.length; i++) {
                    if (a[i].className.indexOf("resource-external-link") >= 0){ 
                        tmp_data.push(a[i].innerText);
                        tmp_data.push(a[i].href);
                    }
                } 

                for (i = 0; i < tmp_data.length / 2; i++) {
                    data.push(tmp_data[i]);
                } 
                
                external_links = data;
                utils.WriteINI( path + "\\" + clean(artist) + "_artist_info.ini", clean_ini(clean(artist)), "external_links", data.join("*"));
                
                doc.close();							
            } 
        }
    }							
}

function print(msg) {
    try {    
        fb.trace(msg);   
    } catch(e){console.log(msg);};         
}
					
function on_notify_data(name, info) {
    if (name == "panel") {
        if (info == "bio"){
            panel_on = true;
            meta_artist = "";
            on_metadb_changed();
        } else {
            panel_on = false;
        }
    }
}

//  Cut text

function cut_text(){
    var text_rows_per_script_panel = Math.floor(window.Height / text_row_height); 

    if (ch() == "lyrics" && !history_on) return;
    if (text_rows < text_rows_per_script_panel) return;

    cut = true;
            
    scroll_ = scroll__ = scroll___ = scroll;
            
    if (Math.abs(scroll) / text_row_height <= info_text_arr.length / 2){
        idx1 = 0;
    } else {
        idx1 = (Math.abs(scroll) / text_row_height) - info_text_arr.length / 2;
    }

    idx1_d = Math.max(0, (idx1 + text_rows_per_script_panel) - text_rows );
            
    k2 = (t_x - t_margin) / (Math.max(ww - t_margin * 2 - seekbar_w - 10, 0));
    k4 = (t_y - t_margin) / (Math.max(wh - t_margin * 2, 0));

    idx2 = text_rows_per_script_panel + Math.round(text_rows_per_script_panel * k2) + Math.round(text_rows_per_script_panel * k4);
            
    text_old = text;
    if (info_text) info_text_old = info_text.join("*");
       

    if (!history_on) {
        text_arr_tmp = text_arr_tmp.splice((idx1 - idx1_d) * 2, idx2 * 2);
        text = "";
            
        for (var i = 0; i < text_arr_tmp.length; i += 2) {
            if (!text_arr_tmp[i]){
                text = text + "\n\n";
            } else {
                text = (text + text_arr_tmp[i]);
            }
        }
    }

    text = text.replace(/^\n/g, "");

    if (history_on) {
        history_arr = history_arr.splice((idx1 - idx1_d) * 2, idx2 * 2); 
        history = [];
       
        for (var i = 0; i < history_arr.length; i += 2) {
            history.push(history_arr[i]);
        }
    }

    scroll_cut = scroll;

    if (Math.abs(scroll) / text_row_height <= info_text_arr.length / 2){
        s = scroll_cut;
    } else {
        s = 0;
        info_text = [];                
    }

    scroll_d = idx1_d * text_row_height;
    scroll = scroll_ = scroll__ = scroll___  = s - scroll_d;

    get_text_arr(true);  
}

function restore_cut_text(){
    if (!cut) return;
    cut = false;

    if (!history_on) {
        if (info_text_old) info_text = info_text_old.split("*");
        text = text_old;
    }
    
    if (history_on) {
        get_history();
    }
    
    scroll = scroll_ = scroll__ = scroll___ = scroll_cut;
    get_text_arr(true);  
}

function img_to_object(n) {
    if (!n) return;
    var object;
    
    if (typeof n == 'object') {
        object = resize_image(n);
    } else { 
        object = resize_image(gdi.Image(n));
    }
    return object;
}


function get_embedded_covers(path) {    //0 - front cover; 1 - back cover; 2 - disc; 3 - icon; 4 - artist;  
    embedded = [];
    embedded_img_name = [];
    
    if (path.indexOf('://') > 0) return;

    if ( metadb ) {
        for (var i = 0; i < 5; i++) {
            var temp = utils.GetAlbumArtEmbedded(path, i);
            //var temp = utils.GetAlbumArtEmbedded(metadb.RawPath, i);
            if (temp) embedded.push(temp);
            if (temp) embedded_img_name.push(attached_img_name[i]);
        }
    }
}

function get_external_covers(path, artist, album) {
    var covers_dir = [];
    var covers_root = [];
    var covers_dir_subs = [];
    var covers_root_subs = [];
    var covers_external = [];
    external = [];
    
    if (path.indexOf('://') > 0) return;

    try {
        dir = fso.GetFolder(path);
        get_covers_from_dir(covers_dir, dir);
        
        root = dir.ParentFolder;
        get_covers_from_dir(covers_root, root);
    
        var e = new Enumerator( dir.SubFolders );
        for(; !e.atEnd(); e.moveNext() ) {
            get_covers_from_dir(covers_dir_subs, e.item() );
        }

        var e = new Enumerator( root.SubFolders );
        for(; !e.atEnd(); e.moveNext() ) {
            var name = e.item().Path;
            var sub_root_name = name.substr(name.lastIndexOf("\\") + 1, name.length);
            for (i in root_folders) {
                if (sub_root_name.toLowerCase().indexOf(root_folders[i].toLowerCase()) == 0) {
                    get_covers_from_dir(covers_root_subs, e.item() );
                }
            }
        }
    } catch(e) {};
    
    covers_external = covers_external.concat(covers_dir, covers_dir_subs, covers_root, covers_root_subs);

    if (covers_external.length > 0) {
        for (i in covers_external) {
            var name = covers_external[i];
            if ( name && get_fn(name).toLowerCase() == album.toLowerCase() )   {
                external.push(name);
                covers_external[i] = null;
            }
        }
        
        for (i in covers_external) {
            var name = covers_external[i];
            if ( name && get_fn(name).toLowerCase() == artist.toLowerCase() )   {
                external.push(name);
                covers_external[i] = null;
            }
        }

        for (i in covers_external) {
            var name = covers_external[i];
            try {
                if ( name && (get_fn(name).toLowerCase().match(artist.toLowerCase()) && get_fn(name).toLowerCase().match(album.toLowerCase())) ) { 
                    external.push(name);
                    covers_external[i] = null;
                }
            } catch(e) {};
        }
        
        for (i in covers_external) {
            var name = covers_external[i];
            if ( name && get_fnext(name).match(/.*(cover|front|folder|album).*/i) ) {
                external.push(name);
                covers_external[i] = null;
            }
        }
        
        for (i in covers_external) {
            var name = covers_external[i];
            if ( name && get_fnext(name).match(/.*back.*/i) ) {
                external.push(name);
                covers_external[i] = null;
            }
        }
        
        for (i in covers_external) {
            var name = covers_external[i];
            if ( name && get_fnext(name).match(/.*cd.*/i) ) {
                external.push(name);
                covers_external[i] = null;
            }
        }

        for (i in covers_external) {
            if (typeof(covers_external[i]) == 'string' ) external.push(covers_external[i]);
        }
    }
}

function get_covers_from_dir(array, dir) {
    var e = new Enumerator( dir.Files );
    while (!e.atEnd()) {
        var name = e.item().Name;
        if (name.match(/\.(jpg|jpeg|png|gif|bmp|tiff)$/i)) {
            array.push( e.item().Path );
        }
        e.moveNext();
    }
}

function get_embedded_img_name(n){
    if (set_priority == 0) {
        idx = n - external.length;
    }
    if (set_priority == 1) {
        idx = n;
    }
    return embedded_img_name[idx];
}

function formatFileSize(b){
    if (b > 1024 * 1024){
        b = Math.round(b / 1024 / 1024 * 100) / 100 + " MB" 
    } else if (b > 1024){
        b = Math.round(b / 1024 * 100) / 100 + " KB" 
    } else { 
        b = b + " Bytes"; 
    }
    return b;
}

function get_covers_info(d){
    if (covers.length){  
        if (covers[d]) {
            if (typeof covers[d] != 'object'){
                if(fso.FileExists(covers[d])){
                    var cover_name = get_fnext(covers[d]);
                    var cover_width = gdi.Image(covers[d]).Width;
                    var cover_height = gdi.Image(covers[d]).Height;
                    var cover_size = formatFileSize(fso.GetFile(covers[d]).size); 
                    var cover_dim = cover_width + " x " + cover_height + ",  " + cover_size;
                }
            }
           
            if (typeof covers[d] == 'object'){
                var cover_name = get_embedded_img_name(d);
                var cover_width = covers[d].Width;
                var cover_height = covers[d].Height;
                var cover_dim = "embedded  " + cover_width + " x " + cover_height;
            }
            
            var n_imgs_1 = covers.length > 1 ? d + 1 + " " : "";
            var n_imgs_2 = external.length > 0 && embedded.length > 0 ? "(" + covers.length + ") " : "";
            var n_imgs_3 = external.length > 0 ? "" + (embedded.length == 0 && external.length > 1 ? "(" + external.length + ")" : external.length) + " external " : "";
            var n_imgs_4 = embedded.length > 0 ? "" + (external.length == 0 && embedded.length > 1 ? "(" + embedded.length + ")" : embedded.length) + " embedded " : "";
            var n_imgs = n_imgs_1 + n_imgs_2 + (set_priority == 0 ? n_imgs_3 + n_imgs_4 : n_imgs_4 + n_imgs_3);
        }
    }
    
    cover_name = cover_name ? cover_name+ "\n" : "";
    cover_dim = cover_dim ? cover_dim+ "\n" : "";
    n_imgs = n_imgs ? n_imgs : "";
    
    ci = cover_name + cover_dim + n_imgs;

    if (set_external && !set_embedded && external.length == 0) ci = "No external covers";
    if (set_embedded && !set_external && embedded.length == 0) ci = "No embedded covers";
    if (set_external && set_embedded && covers.length == 0) ci = "No covers";

    temp_bmp = gdi.CreateImage(1, 1);
    temp_gr = temp_bmp.GetGraphics();

    ci_text_row_width = Math.max(ww - t_margin * 2, 0);
    
    var ci_text_arr_tmp = temp_gr.EstimateLineWrap(ci, t2_font, ci_text_row_width).toArray();
    ci_text_arr = [];
    for (var i = 0; i < ci_text_arr_tmp.length; i += 2) {
        ci_text_arr.push(trim(ci_text_arr_tmp[i]));
    }

    ci_text_row_height = temp_gr.CalcTextHeight("Covers info", t2_font);
    ci_text_height = ci_text_row_height * ci_text_arr.length;

    temp_bmp.ReleaseGraphics(temp_gr);
    temp_bmp.Dispose();
    temp_gr = null;
    temp_bmp = null;
}

function next_image_covers(d){
    if (d < 0) {img_selected = img_selected <= 0 ? covers.length - 1 : img_selected = img_selected - 1};
    if (d > 0) {img_selected = img_selected >= covers.length - 1 ? 0 : img_selected = img_selected + 1};
    
    var color_scheme_0 = [];   
    if (g_img){
        try {
            color_scheme_0 = g_img.GetColorScheme(100).toArray(); 
        } catch(e) {}; 
        try {
            color_scheme_0 = JSON.parse(g_img.GetColourSchemeJSON(100));
        } catch(e) {}; 
    }

    if (typeof covers[img_selected] == 'object') {
        g_img = resize_image(covers[img_selected]);
    } else { 
        g_img = resize_image(gdi.Image(covers[img_selected]));
    } 

    if (g_img) img_size_recount = true;

    var color_scheme_1 = [];
    var compare = true;

    if (g_img){
        try {
            color_scheme_1 = g_img.GetColorScheme(100).toArray();
            for( var i = 0; i < Math.min(color_scheme_0.length, color_scheme_1.length); i++ ){
                if (color_scheme_0[i] != color_scheme_1[i]){
                    compare = false;
                    break;
                }
            }
        } catch(e) {};
        try {
            color_scheme_1 = JSON.parse(g_img.GetColourSchemeJSON(100));
            for( var i = 0; i < Math.min(color_scheme_0.length, color_scheme_1.length); i++ ){
                if (color_scheme_0[i].col != color_scheme_1[i].col){
                    compare = false;
                    break;
                }
            }
        } catch(e) {};
    }

    if (!compare || color_scheme_0.length == 0 || color_scheme_1.length == 0){
        fader = fade_effect ? 0 : 255; 
    } else {
        fader = 255; 
    }

    get_covers_info(img_selected);

    def_fader_ini();
    if (g_img && fade_effect) fader_timer();
    window.Repaint();
}

function get_covers() {
    img_selected = 0;
    ci_text_arr = [];
    
    external = set_external ? external : [];
    embedded = set_embedded ? embedded : [];
    
    covers = [];
   
    if (set_priority == 0) {
        covers = covers.concat(external, embedded);
    }
    if (set_priority == 1) {
        covers = covers.concat(embedded, external);
    }

    def_img_cover = covers.length ? img_to_object(covers[0]) : null;
    def_img_ini();

    covers_on && next_image_covers(0);
}




